R:如何根据值填充箱线图

hgc7kmma  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(118)

我有一个小问题。我想对箱线图的颜色进行正确的排序。对于较低的值,颜色较冷,对于较高的值,颜色较暖。在我的示例中有错误的排序。
有什么办法吗?

library(ggplot2)

#  data
set.seed(123)  
data <- data.frame(tavg = sample(-30:30, 2000, replace = TRUE),
                   attendance = sample(100:30000, 1000, replace = TRUE))

my_colors <- viridisLite::viridis(length(unique(cut(data$tavg, seq(-20, 30, 5)))))

ggplot(data, aes(x = cut(tavg, seq(-20, 30, 5)), 
                 y = attendance, 
                 fill = factor(cut(tavg, seq(-20, 30, 5)), 
                 levels = unique(cut(tavg, seq(-20, 30, 5))))))+
         geom_boxplot(outlier.shape = NA) +
         geom_jitter(color = "black", size = 0.4, alpha = 0.1) +
         scale_fill_manual(values = my_colors) +
         labs(x = "Temperature", y = "Attendance", fill="Sequence") +
         ggtitle("Title") +
         theme_minimal()
3yhwsihp

3yhwsihp1#

问题是,使用不必要的factor(cut(tavg, seq(-20, 30, 5)), levels = unique(cut(tavg, seq(-20, 30, 5))会打乱cut返回的正确排序的factor的顺序。总的来说,我建议在数据中添加一列,然后将其Map到xfill上:

library(ggplot2)

#  data
set.seed(123)

data <- data.frame(
  tavg = sample(-30:30, 2000, replace = TRUE),
  attendance = sample(100:30000, 1000, replace = TRUE)
)

data$tavg_binned <- cut(data$tavg, seq(-30, 30, 5), include.lowest = TRUE)

my_colors <- viridisLite::viridis(length(levels(data$tavg_binned)))

ggplot(data, aes(
  x = tavg_binned,
  y = attendance,
  fill = tavg_binned
)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(color = "black", size = 0.4, alpha = 0.1) +
  scale_fill_manual(values = my_colors) +
  labs(x = "Temperature", y = "Attendance", fill = "Sequence") +
  ggtitle("Title") +
  theme_minimal()

相关问题