Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot(p) and plot(ggplot_gtable(ggplot_build(p))) don't seem to give same output when plot background is transparent

Tags:

r

ggplot2

I have the following R ggplot code:

require(ggplot2)
require(ggthemes)

df <- data.frame(x=1:10, y=5*(1:10))

p <- ggplot(df, aes(x,y)) +
   geom_point() +
   theme_few() +
   theme(plot.background = element_rect(fill='transparent', colour=NA), legend.position='top')

pdf('test.pdf', width=5, height=2)

plot(p)

plot(ggplot_gtable(ggplot_build(p)))

But I do get two different figures:

enter image description here

enter image description here

I like the first figure (i.e without the background grid outside panel area). However, I also need to use ggplot_build() for some other processing. Could you please help?

like image 296
Soumitra Avatar asked Jun 20 '26 13:06

Soumitra


1 Answers

You could copy what ggplot2::print.ggplot does more directly. This seems to work.

pdf('test.pdf', width=5, height=2)

plot(p)

grid::grid.newpage()
grid::grid.draw(ggplot_gtable(ggplot_build(p)))

dev.off()
like image 163
MrFlick Avatar answered Jun 23 '26 19:06

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!