ggplot2:: 在所有面板中使用相同参考图的分面图

ggplot2:: Facetting plot with the same reference plot in all panels

我想分面绘制一个图,但每个面板中都有一个参考图。让我尝试用图片展示我想要实现的目标:我的例子 data_frame:

require(dplyr)

df <- data_frame( id = c(rep('ctr',40), rep('pat',80)),
                  class = c(rep('ctr',40), rep(c('a','b'), each = 40)),
                  rank =  rep (1:20,6),
                  mean = c(rep(seq(3,-3, length.out = 20),2), 
                           rep(seq(1,-4, length.out = 20),2), 
                           rep(seq(-2,-8, length.out = 20),2)),
                  sd = rep(seq(1.2,0.8, length.out = 20), times = 6),
                  exam = rep(c('blue','red'), each = 20, times = 3))

我的剧情:

# first, create reference plot of the 'controls'
require(ggplot2)
p_ctr <- ggplot() + 
 geom_line(data = filter(df, id == 'ctr'),
            aes(x=rank, y=mean, color=exam), linetype=1) + 
  geom_ribbon(data = filter(df, id == 'ctr'),
              aes(x = rank, ymax = mean+sd, ymin = mean-sd, 
                  fill = exam), alpha = .1) +
  scale_colour_manual(values = c("#00b6eb","#eb0041")) + 
  scale_fill_manual(values = c("#00b6eb","#eb0041")) 

# then, overlay with plot of 'patients'

p_ctr + geom_line(data = filter(df, id == 'pat'), 
              aes(x=rank, y=mean, linetype = class)) +
  geom_ribbon(data = filter(df, id == 'pat'), 
              aes(x = rank, ymax = mean+sd, ymin = mean-sd,
                  group = class), 
              alpha = .1) +
  facet_wrap(~exam)

到一半了: 然而,理想情况下,我想在单独的面板中绘制不同的 "classes",但在每个面板中使用控制图作为参考:

预期结果

我尝试了不同的分面组合,但没有很好的效果。我想,一定有一个简单的解决方案吧?

也许是这样。

library(dplyr)
library(ggplot2)

df1 <- filter(df, id == 'ctr')
df2 <- filter(df, id == 'pat')
df2 <- dplyr::rename(df2, class_2 = class)

p_ctr <- ggplot() + 
 geom_line(data = df1, aes(x=rank, y=mean, color=exam)) +
 geom_ribbon(data = df1,
             aes(x = rank, ymax = mean+sd, ymin = mean-sd, fill = exam),
             alpha = .1) +
 scale_colour_manual(values = c("#00b6eb","#eb0041")) +
 scale_fill_manual(values = c("#00b6eb","#eb0041")) +
 geom_line(data = df2,
           aes(x=rank, y=mean)) +
 geom_ribbon(data = df2,
             aes(x = rank, ymax = mean+sd, ymin = mean-sd),
             alpha = .1) +
 facet_grid(class_2 ~ exam)

p_ctr

使用 facet_wrap 会出现以下错误:

error in gList(list(x = 0.5, y = 0.5, width = 1, height = 1, just = "centre", : only 'grobs' allowed in "gList"


您可能在寻找解决方案时遇到了这个情节。

p_ctr + geom_line(data = filter(df, id == 'pat'), 
                  aes(x=rank, y=mean)) +
        geom_ribbon(data = filter(df, id == 'pat'), 
                    aes(x = rank, ymax = mean+sd, ymin = mean-sd), 
                    alpha = .1) +
      # facet_wrap(~exam) +
        facet_grid(class ~ exam)

这基本上是您的参考图及其覆盖图,没有 linetypegroup 参数。此外,我还遇到了 class ~ exam。从此图中,您可以看到 'the problem' 是 class 包含三个独特的元素:abctr。这就是为什么我将 df2 中的变量 class 重命名为 class_2,它只有两个唯一元素:ab。通过 class_2 ~ exam 分面然后给出所需的输出。

希望对您有所帮助。