plot only a select few facets in facet_grid

2020-02-09 11:57发布

问题:

I was looking for a way to plot using facet_grid in ggplot2 that only displays just a few select facets. say I have the following plot:

Been looking for a quick way to, for instance, just plot facets 1 and 3.

#data
y<-1:12
x<-c(1,2,3,1,2,3,1,2,3,1,2,3)
z<-c("a","a","a","b","b","b","a","a","a","b","b","b")
df<-as.data.frame(cbind(x,y,z))

#plot

a <- ggplot(df, aes(x = z, y = y,
  fill = z))
b <- a + geom_bar(stat = "identity", position = "dodge")
c <- b + facet_grid(. ~ x, scale = "free_y")
c

Obviously I figured out how to just chop up my data first but this must of course be possible to allocate in ggplot2 Even just a nudge would be most welcome.

回答1:

Use subset in your ggplot call.

plot_1 = ggplot(subset(df, x %in% c(1, 2)), aes(x=z, y=y, fill=z)) +
         geom_bar(stat = "identity", position = "dodge") +
         facet_grid(. ~ x, scale = "free_y")



回答2:

Would this be okay,

a <- ggplot(subset(df, x != 2), aes(x = z, y = y, fill = z))
b <- a + geom_bar(stat = "identity", position = "dodge")
c <- b + facet_grid(. ~ x, scale = "free_y")
c


标签: r ggplot2