【发布时间】:2020-10-05 03:45:19
【问题描述】:
假设我有一个包含序数变量和分类变量的数据:
set.seed(35)
df <- data.frame(Class = factor(rep(c(1,2),times = 80), labels = c("Math","Science")),
StudyTime = factor(sort(sample(1:4, 16, prob = c(0.25,0.3,0.3,0.15), replace = TRUE)),labels = c("<5","5-10","10-20",">20")),
Nerd = factor(sapply(rep(c(0.1,0.3,0.5,0.8),c(30,50,50,30)), function(x)sample(c("Nerd","NotNerd"),size = 1, prob = c(x,1-x))),levels = c("NotNerd","Nerd")))
可以使用ggplot 和geom_bar 与x、fill 和alpha(或color)美学映射来可视化这些变量之间的关系。
ggplot(data = df, aes(x = Class, fill = StudyTime, alpha = Nerd)) +
geom_bar(position = "dodge", color = "black") +
scale_alpha_manual(values = c(Nerd = 0.5, NotNerd = 1)) +
scale_fill_manual(values = colorRampPalette(c("#0066CC","#FFFFFF","#FF8C00"))(4)) +
labs(x = "Class", y = "Number of Students", alpha = "Nerd?") +
theme(legend.key.height = unit(1, "cm"))
但是,alpha 和 color 并不理想。更好的选择可能是应用条纹或交叉影线等图案。
10 多年前对this question 的公认答案是使用颜色,而the most upvoted answer(虽然聪明)使用超过 100 行代码。
This question 收到了一些赞成票,但没有新的答案。
有没有更好的选择来添加一个模式,比如可以在这里看到?
【问题讨论】: