ggplot2: create a plot using selected facets with

2019-07-27 12:57发布

问题:

I would like to create a plot with

  1. Using part of the data to create a base plot with facet_grid of two columns.
  2. Use remaining part of the data and plot on top of the existing facets but using only a single column.

The sample code:

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)

The output plots:

How to include g3 plot on g2 plot? The resulting plot should include the g3 two lines twice on two facets.

回答1:

I assume the plot below is what you were looking for.

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

explaination

For tasks like this I found it better to work with two datasets. Since the variable df2$class has three unique values: A, B and C, faceting Class~Type does not give you desired plot, since you want the data for df2$Class == "A" to be displayed in the respective facets.

That's why I renamed variable Class in df_1 to Class_1 because this variable only contains two unique values: B and C. Faceting Class_1 ~ Type allows you to plot the data for df2$Class == "A" on top without being faceted by Class.

edit

Based on the comment below here is a solution using only one dataset

g2 + geom_line(data = filter(df2, Class == 'A')[, -1], 
               aes(X, Y, linetype = Type, col = "A"))

Similar / same question: ggplot2:: Facetting plot with the same reference plot in all panels