簡體   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