在 geom_tile() 中向 x 轴添加组标签
我希望向 geom_tile() x 轴上的变量添加一个总体分组标签。
最好的办法(不使用 geom_text() 并在 x 轴变量上方手动添加组 1、组 2 和组 3)就是这样,它只是创建一个新的包含两部分信息的变量:
set.seed(1)
df <- expand.grid(group = c("Group 1", "Group 2", "Group 3"),
xVar = c("A", "B"),
yVar = c("x","y","z")) %>%
mutate(fillValue = factor(sample(c(0,1), 18, TRUE))) %>%
mutate(group_and_xVar = paste(group, xVar, sep = "\n"))
ggplot(df, aes(x = group_and_xVar, y = yVar, fill = fillValue))+
geom_tile(colour = "black") +
scale_x_discrete(position = "top", expand = c(0,0))+
scale_y_discrete(expand = c(0,0))+
scale_fill_manual(values=c("#FF4933", "#72AF4A"))+
labs(x = "", y = "", fill = "")+
theme_bw()+
theme(axis.text.x = element_text(angle = 0, vjust = .05),
legend.position = "none")
这不是我想要的。我希望每个组只在绘图上出现一次,并且代码要进行软编码(适用于将来可能添加的新数据或组)。我也尝试过使用facet_grid/facet_wrap,但我没有运气。
另外调整单元格的高度以使其看起来更像第一张图像将是一个额外的好处:)
I'm looking to add an overarching grouping label to variables on the x-axis of geom_tile().
This is similar to the result I'm looking for:
However, the best I can come up with (WITHOUT using geom_text() and manually adding group 1, group 2 and group 3 above the x-axis variables) is this, which just creates a new variable containing both pieces on information:
set.seed(1)
df <- expand.grid(group = c("Group 1", "Group 2", "Group 3"),
xVar = c("A", "B"),
yVar = c("x","y","z")) %>%
mutate(fillValue = factor(sample(c(0,1), 18, TRUE))) %>%
mutate(group_and_xVar = paste(group, xVar, sep = "\n"))
ggplot(df, aes(x = group_and_xVar, y = yVar, fill = fillValue))+
geom_tile(colour = "black") +
scale_x_discrete(position = "top", expand = c(0,0))+
scale_y_discrete(expand = c(0,0))+
scale_fill_manual(values=c("#FF4933", "#72AF4A"))+
labs(x = "", y = "", fill = "")+
theme_bw()+
theme(axis.text.x = element_text(angle = 0, vjust = .05),
legend.position = "none")
This is not what I want. I'd like to have each group only appear once on the plot and for the code to be soft coded (adaptable to new data or groups that might be added in the future). I've also attempted using facet_grid/facet_wrap but I haven't had luck with those.
Also adjusting the height of the cells to look more like the first image would be a bonus :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
受此帖子启发的解决方案:
A solution inspired by this post: