我有一个小问题。我想对箱线图的颜色进行正确的排序。对于较低的值,颜色较冷,对于较高的值,颜色较暖。在我的示例中有错误的排序。
有什么办法吗?
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()
1条答案
按热度按时间3yhwsihp1#
问题是,使用不必要的
factor(cut(tavg, seq(-20, 30, 5)), levels = unique(cut(tavg, seq(-20, 30, 5))
会打乱cut
返回的正确排序的factor
的顺序。总的来说,我建议在数据中添加一列,然后将其Map到x
和fill
上: