Feng Tian
Feng Tian

Reputation: 1589

Convert gtable into ggplot in R ggplot2

Although gtable could be converted into ggplot using ggplotify::as.ggplot, the output is different from the origin ggplot. For example:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
g <- ggplot_gtable(ggplot_build(p))
p_new <- ggplotify::as.ggplot(p)

# origin
p + theme(aspect.ratio = 2)

# changed
p_new + theme(aspect.ratio = 2)   # different figure shape from the origin one

How could I covert gtable into the same ggplot p_new as the origin one p?

Upvotes: 4

Views: 2379

Answers (2)

Derek Chiu
Derek Chiu

Reputation: 11

Use patchwork::wrap_ggplot_grob() on g instead of ggplotify::as.ggplot() for proper alignment.

See the patchwork gtable docs for more details.

Upvotes: 1

s__
s__

Reputation: 9485

You can use ggplotify::as.ggplot():

library("ggplotify")
as.ggplot(q)

Upvotes: 7

Related Questions