r - Saving a graph with ggsave after using ggplot_build and ggplot_gtable -
i modifying graph built ggplot altering data produced ggplot_build (for reason similar include space missing factor level used in fill aesthetics in geom_boxplot). far understand found on topic, should able save result applying ggplot_gtable , arrangegrob before calling ggsave on results (saving grid.arrange() plot file).
however obtain error "plot should ggplot2 plot", simple reproductible example:
require('ggplot2') require('gridextra') df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")), f2=factor(rbinom(100, 1, 0.45), label=c("young","old")), boxthis=rnorm(100)) g <- ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot() dd <- ggplot_build(g) # printing graph works: print(arrangegrob(ggplot_gtable(dd))) # saving graph doesn't: ggsave('test.png',arrangegrob(ggplot_gtable(dd)))
can explain why not work ? there way use ggsave after modifying data using ggplot_build() ?
(my version of packages gridextra_0.9.1 , ggplot2_0.9.3.1)
it not work because ggsave
wants object of class ggplot
, while you're passing grob. arrangegrob
trick ggsave
in pretending inheritance ggplot
, when @ least 1 of grobs belongs class; here, however, you're passing gtable
.
perhaps easiest workaround clone ggsave , bypass class check,
ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2]
edit: dev version of ggplot2 no longer requires hack*, ggsave
now works grob.
*ps: hack works no longer, arrangegrob returns gtable, , print method not draw on device.
Comments
Post a Comment