2

I want to alter a ggplot2 plot in R using the ggplot_build and ggplot_gtable functions and use it afterwards in a plot_grid.

Example code to make the plot:

library(ggplot2) 
library(cowplot)

p1 <- ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +
  geom_point()
p2 <- ggplot(iris) +
  aes(x = Petal.Length, y = Petal.Width, colour = Species) +
  geom_point()

plot_grid(p1, p2)

Then I change p1 using ggplot_build and ggplot_gtable:

q1 <- ggplot_build(p1)
q1$data[[1]]$colour <- "black"
q1 <- ggplot_gtable(q1)

plot(q1) plots the plot that I want but I can not use it in plot_grid with plot_grid(q1, p2). How can I solve this?

Edit: Code should have indeed worked. After a complete R restart everything worked as expected. Should have tried this first, apologies!

pjvdam88
  • 21
  • 1
  • 4

2 Answers2

4

When calling to print/plot a ggplot2, what really happens in the background is:

data <- ggplot_build(x)
gtable <- ggplot_gtable(data)

where x is your ggplot2 object (p1 og p2). (See ggplot2:::plot.ggplot.) Other routines uses ggplotGrob(x), which is synonymous to ggplot_gtable(ggplot_build(x)).

Short story: gtable is not a ggplot2 object. It's a grob object. And there is not defined a plot or print method for grob objects. They must instead be drawn with the grid package.

To draw your q1 and q2, use:

library(grid)
grid.newpage()
grid.draw(q1)
MrGumble
  • 5,631
  • 1
  • 18
  • 33
2

Would you mind running your code through the reprex package and then posting the result here? Something isn't working right on your end. The code you post should work as expected (see below).

Note that I'm running the development version of cowplot, but the only visible difference is going to be the theme. Using gtables in plot_grid() has worked for years.

library(ggplot2) 
library(cowplot)
#> 
#> 
#> *******************************************************
#> Note: cowplot does not change the default ggplot2 theme
#> anymore. To recover the previous behavior, execute:
#>   theme_set(theme_cowplot())
#> *******************************************************

p1 <- ggplot(iris) +
  aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +
  geom_point()
p2 <- ggplot(iris) +
  aes(x = Petal.Length, y = Petal.Width, colour = Species) +
  geom_point()

plot_grid(p1, p2)

q1 <- ggplot_build(p1)
q1$data[[1]]$colour <- "black"
q1 <- ggplot_gtable(q1)
plot_grid(q1, p2)

Created on 2018-12-17 by the reprex package (v0.2.1)

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104