如何在R中使用ggplot添加“分组”标签?

3
我使用ggplot在R中制作了一个热度图。 示例
# Libraries
library(tidyverse)

# Create data frame
df <- data.frame(test = rep(c("testA-01", "testA-02", "testA-03", "testB-01", "testB-02", "testB-03", "testC-01", "testC-02", "testC-03"),3), 
                 time = c( rep(0,9), rep(1, 9), rep(2, 9) ), 
                 score = sample(1:10, 27, replace = TRUE) )

# Create heatmap
ggplot(data = df, mapping = aes(x = time, y = test)) +
  geom_tile(mapping = aes(fill = score, width=0.9, height=0.9)) +
  scale_fill_gradientn(limits = c(1,10), colours=c("grey95", "grey40", "red"), na.value = "white" ) +
  scale_y_discrete(name = "Test", limits = c("testC-03", "testC-02", "testC-01", "testB-03", "testB-02", "testB-01", "testA-03",
                                                "testA-02", "testA-01")) +
  theme_classic()

这导致了以下的绘图结果:

enter image description here

我想将y轴上的标签捆绑在一起,以便我不必为每个测试重复三次“Test[letter]”。我可以手动完成它,但我想也许可以使用ggplot。解决方案的第一部分是从scale_y_discrete()limits中删除“Test[letter]”部分。接下来,我想在y轴上垂直添加并按测试分组标签(最好用一条垂直线分组测试),就像这样:

期望结果: enter image description here

在ggplot中是否可能实现这一点?如果可以,请告诉我如何实现。

@Henrik 感谢您的建议,我已经能够弄清如何在每个轴上添加“两个标签”(作为下面的答案发布)。但是,我不确定如何添加一个垂直线到图形外部,以便按方面分组变量。有什么想法吗? - user213544
好的图表!我明白你的请求,但你也可以考虑一个更简洁的替代方案,例如在面板之间创建一个微小的间隙,例如 panel.spacing = unit(0.1, "cm")(或者您认为在最终呈现的图表中看起来好的任何价值)。然后轴本身成为垂直线,多余的线可能是冗余的。但这只是我个人对数据墨水比的简洁方法。祝你好运! - Henrik
1个回答

4
一些数据框的重新排列可以简化绘图:
df <- data.frame(batch = c( rep("TestA",9), rep("TestB", 9), rep("TestC", 9) ), 
                 test = rep(c(1,2,3),9), 
                 time = rep(c(0,0,0,1,1,1,2,2,2),3), 
                 score = sample(1:10, 27, replace = TRUE) )

图表

使用 facet_grid() 函数可以对绘制的数据进行分面。结合 ggplotannotation_custom()coord_cartesian() 函数,可以添加“分组”线条。

library(tidyverse)
library(grid)

ggplot(data = df, mapping = aes(x = time, y = test)) +
geom_tile(mapping = aes(fill = score, width=0.9, height=0.9)) +
scale_fill_gradientn(limits = c(1,10), colours=c("grey95", "grey40", "red"), na.value = "white" ) +
theme_classic() +
scale_y_reverse() +
facet_grid(batch ~ ., space="free_x", scales="free_y", switch="y") +
theme(strip.placement = "outside",
      strip.background = element_rect(fill=NA,colour=NA),
      panel.spacing=unit(0,"cm"), axis.title.y = element_blank()) +
annotation_custom(grob = linesGrob(), xmin = -0.75, xmax = -0.75, ymin = -3.25, ymax = -0.75) +
coord_cartesian(clip="off") 

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接