Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract single plot from ggplot with facet_grid

Tags:

r

ggplot2

facet

I want to produce some plots using ggplot and facet_grid and save the plot as an object. My problem is that I also want to save each subgroup (i.e. each facet) as an object separately. My question is now if you can extract a single facet from facet_grid and save it as an object? Here is some simple code:

library(ggplot2)

ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_grid(. ~ am)

Now I'd like to produce two objects - one for am=0 and one for am=1.

like image 407
ehi Avatar asked Oct 24 '16 12:10

ehi


People also ask

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data. If you have only one variable with many levels, try facet_wrap() .

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

Can you facet wrap by 2 variables?

Note that you can add as many (categorical) variables as you'd like in your facet wrap, however, this will result in a longer loading period for R.

What does Facet_wrap do in Ggplot?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.


1 Answers

I'm not sure why you wouldn't use subsetting, but you can extract individual facets from a facet grid.

library(ggplot2)
library(grid)
library(gtable)

p1 = ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_grid(. ~ am)


g1 = ggplotGrob(p1)


# Rows and columns can be dropped from the layout.

# To show the layout:
gtable_show_layout(g1)

# Which columns (and/or rows) to drop?
# In this case drop columns 5 and 6 to leave am = 0 plot
# Drop columns 4 and 5 to leave am = 1 plot

# am = 0 plot
g1_am0 = g1[,-c(5,6)]

grid.newpage()
grid.draw(g1_am0)


# am = 1 plot
g1_am1 = g1[,-c(4,5)]

grid.newpage()
grid.draw(g1_am1)
like image 106
Sandy Muspratt Avatar answered Sep 19 '22 20:09

Sandy Muspratt