R语言 ggplot生成带有两个y轴标签的堆叠条形图

oogrdqng  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(210)

我试着用一个seurat对象元数据复制下面的堆叠条形图样式。enter image description here x1c 0d1x
下面是我尝试生成的代码。

p1 <- ggplot(meta_data, aes(y = interaction (cohort, factor(meta_data$patient_ID,levels = rev(patient_ID_reorder)), sep = " "),  
                      fill =  celltype), group = 1) + 
  geom_bar(position = "fill")+
  theme(axis.title.x=element_blank(),
         axis.text.x = element_blank(),
         axis.ticks.x=element_blank(),
         axis.title.y=element_blank(),
         axis.ticks.y=element_blank(),
         panel.background = element_blank()
        )+
  scale_fill_brewer(palette = "Set1")+
  ggtitle("Cell type proporation") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

我尝试了facet_wrap(~ cqueue),它生成了一个如下所示的面板。enter image description here


但是,我不知道如何使用不同颜色的矩形来替换“mono”和“combo”,并增加“mono”和“combo”之间的空间。
任何帮助都是appriciated!
我已经尝试了我所寻找的所有方法,但都失败了。

92dk7w1h

92dk7w1h1#

这里有一种方法可以让你接近你想要的结果,使用ggh4x::facet_nested作为嵌套面,ggnewscale::new_scale_fill作为第二个填充比例,patchwork添加列标签。最后,对于cohort的彩色条,我使用geom_col,并通过geom_text添加轴文本。
使用一些伪随机示例数据:

meta_data <- data.frame(
  patient_ID = paste0("P", seq(20)),
  cohort = c(rep("mono", 3), rep("combo", 3), rep("mono", 7), rep("combo", 7)),
  celltype = rep(letters[1:5], each = 20),
  type = c(rep("pre", 6), rep("post", 14))
)

set.seed(123)

meta_data <- meta_data[sample(nrow(meta_data), 1000, replace = TRUE), ]

library(ggplot2)
library(ggh4x)

meta_data$type <- factor(meta_data$type, c("pre", "post"))

p1 <- ggplot(meta_data, aes(
  y = patient_ID
)) +
  geom_bar(aes(fill = celltype), position = "fill") +
  scale_fill_brewer(palette = "Set1") +
  ggnewscale::new_scale_fill() +
  geom_col(data = dplyr::distinct(meta_data, patient_ID, cohort, type), aes(x = -.3, fill = cohort), width = .9) +
  geom_col(data = dplyr::distinct(meta_data, patient_ID, cohort, type), aes(x = -.15), fill = "white", color = "white") +
  geom_text(data = dplyr::distinct(meta_data, patient_ID, cohort, type), aes(x = -.075, label = patient_ID)) +
  scale_fill_brewer(palette = "Set2") +
  scale_x_continuous(expand = c(0, 0)) +
  facet_nested(type + cohort ~ .,
    scale = "free_y", space = "free_y",
    strip = strip_nested(
      by_layer_y = TRUE,
      background_y = list(element_rect(), element_blank()),
      text_y = list(element_text(), element_blank())
    )
  )

p2 <- ggplot() +
  geom_text(data = data.frame(
    y = 21,
    x = c(-.225, -0.075, .5),
    label = c("Cohort", "ID", "Cell type proporation")
  ), aes(x = x, y = y, label = label), fontface = "bold") +
  scale_x_continuous(expand = c(0, 0), limits = c(-.3, 1)) +
  coord_cartesian(clip = "off")

library(patchwork)

p2 + p1 & plot_layout(heights = c(1, 20)) &
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.background = element_blank()
  ) &
  labs(x = NULL, y = NULL)

相关问题