添加第二个小平面网格或第二个离散 y 轴标签 GGPlot2

Add second facet grid or second discrete y-axis label GGPlot2

假设我有这个数据框:

library(ggplot2)
library(dplyr)
library(readr)
library(magrittr)
library(tidyr)

df2 <- data.frame(tissue = c("Blood", "Nerve", "Stomach", "Liver", "Blood", "Kidney"),
                  qtl = c("e", "s", "e", "e", "s", "s"),
                  gene = c("gene1", "gene1", 
                           "gene2", "gene2",
                           "gene3", "gene4"),
                  value = c(0.4, 0.2, 0.1, 0.9, 0.5, 0.3),
                  second_label = c("label1", "label1", "label1","label1",
                                  "label2", "label2"))

我是这样画的:

ggplot(df2, 
       aes(x=tissue, y=qtl,
           size=value))+
  geom_point()+
  facet_grid(rows = vars(gene),
             scales = "free", 
             space='free',
             switch = "y")+
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_blank(),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))

此代码生成下图(见第一张图片)

但是,我想添加第二个小平面环绕,作为“轨迹”并将其放在图的右侧。

这可能吗?我知道在 facet_grid 中,您可以在一个变量是列而另一个变量是行的情况下执行此操作,但我还没有看到如何在两个变量都是行的情况下执行此操作。

我研究过使用 sec.axis 添加辅助 y 轴,但这似乎只适用于连续变量。

提前致谢!

我强烈推荐 ggh4x 包(github link here), which can handle this issue nicely via nested facets 通过 facet_nested()。在这里,你根据 df2$gene 进行分面,但表明这些分面的嵌套是根据df2$qtl.

这是一个代码示例,向您展示了应用于 df2 的一些基本功能。请注意,我更改了一些条带背景格式以使刻面更加清晰。该软件包中还有许多其他选项可能更适合您。

p <-
  ggplot(df2, aes(x=tissue, y=qtl, size=value))+
  geom_point()+
  facet_nested(qtl + gene ~ .) +
  
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_rect(fill='white', color="black"),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))
p