问题是使用不必要的
factor(cut(tavg, seq(-20, 30, 5)), levels = unique(cut(tavg, seq(-20, 30, 5))
你把秩序搞砸了
factor
返回者
cut
。总的来说,我建议在您的数据中添加一次带有binned值的列,然后将其映射到
x
和
fill
以下为:
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()