ggplot2:使用带有零件数据的选定构面创建绘图

时间:2018-01-26 18:04:07

标签: r ggplot2 facet facet-wrap facet-grid

我想用

创建一个情节
  1. 使用部分数据创建两列facet_grid的基础图。
  2. 使用剩余部分数据并在现有构面之上绘图,但仅使用一列。
  3. 示例代码:

    library(ggplot2)
    library(gridExtra)
    
    df2 <- data.frame(Class=rep(c('A','B','C'),each=20), 
                     Type=rep(rep(c('T1','T2'),each=10), 3),
                     X=rep(rep(1:10,each=2), 3),
                     Y=c(rep(seq(3,-3, length.out = 10),2), 
                        rep(seq(1,-4, length.out = 10),2), 
                        rep(seq(-2,-8, length.out = 10),2)))
    
    g2 <- ggplot() + geom_line(data = df2 %>% filter(Class %in% c('B','C')),
                               aes(X,Y,color=Class, linetype=Type)) + 
      facet_grid(Type~Class)
    
    g3 <- ggplot() + geom_line(data = df2 %>% filter(Class == 'A'), 
                               aes(X,Y,color=Class, linetype=Type)) + 
      facet_wrap(~Type)
    
    grid.arrange(g2, g3)
    

    输出图:

    enter image description here

    如何在g3情节中加入g2情节?结果图应在两个方面包括g3两行两次。

1 个答案:

答案 0 :(得分:1)

我认为下面的情节是你要找的。

library(dplyr)
library(ggplot2)
df_1 <- filter(df2, Class %in% c('B','C')) %>% 
 dplyr::rename(Class_1 = Class)
df_2 <- filter(df2, Class == 'A') 

g2 <- ggplot() + 
 geom_line(data = df_1,
           aes(X, Y, color = Class_1, linetype = Type)) +
 geom_line(data = df_2,
           aes(X, Y, color = Class, linetype = Type)) +
 facet_grid(Type ~ Class_1)
g2

enter image description here

<强>的解释

对于这样的任务,我发现使用两个数据集会更好。由于变量df2$class有三个唯一值:ABC,因此您需要数据,因此Class~Type不会为您提供所需的图表df2$Class == "A"显示在各个方面。

这就是我将Class中的变量df_1重命名为Class_1的原因,因为此变量只包含两个唯一值:BC。 通过构面Class_1 ~ Type,您可以在df2$Class == "A"上方绘制Class的数据,而不会被g2 + geom_line(data = filter(df2, Class == 'A')[, -1], aes(X, Y, linetype = Type, col = "A")) 分割。

修改

根据下面的评论,此处是仅使用一个数据集的解决方案

{{1}}

相似/同一问题:ggplot2:: Facetting plot with the same reference plot in all panels