繁体   English   中英

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

[英]How to add “grouped” labels using ggplot in R?

我用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()

这导致以下情节:

在此处输入图片说明

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

预期结果 在此处输入图片说明

在ggplot中这可能吗? 如果是这样,您该怎么做?

数据框的一些重新排列使绘制变得容易:

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()函数可以对图中的数据进行分面。 使用ggplotcoord_cartesian()annotation_custom()函数,我能够添加“分组”行。

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") 

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM