plot only a select few facets in facet_grid

10,111

Solution 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")

enter image description here

Solution 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
Share:
10,111
user1317221_G
Author by

user1317221_G

Updated on July 09, 2022

Comments

  • user1317221_G
    user1317221_G over 1 year

    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:

    enter image description here

    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.