[R] Print grid/ggplot to a metafile

Paul Murrell p.murrell at auckland.ac.nz
Wed Jul 4 02:32:26 CEST 2007


Hi


Dieter Menne wrote:
> Dear UseRs called Hadley, or Paul,
> 
> I am trying to print an edited ggplot2/grid graphics to a metafile. With the
> commented line below it works, but when I edit the plot by uncommenting the
> line, it fails, because it's illegal to have 2 graphics in a metafile. It
> works with pdf, but even then I get two plots, which is a nuisance.
> 
> I found a workaround by using windows(); savePlot, but it only works in
> interactive mode, not when called with something like (Windows)
> 
> rterm --no-save < printit.r
> 
> Any ideas?


You can capture the ggplot drawing as a grid grob (gTree), edit that (no 
drawing occurs to this point), and then draw it ...

gridggplot <- grid.grabExpr(print(ggplot(mtcars, aes(x=cyls)) +
                                   geom_bar()))
modgridggplot <- editGrob(gridggplot,
                           "xaxis::labels::label.text",
                           just=c("center","center"),
                           grep=TRUE, global=TRUE)

win.metafile(file="bar.emf")
grid.draw(modgridggplot)
dev.off()

Paul


> Dieter
> 
> #------
> library(ggplot2)
> win.metafile(file="bar.emf")
> mtcars$cyls = factor(mtcars$cyl,
>   labels=c("four\ncylinders","six\ncylinders","eight\ncylinders"))
> ggplot(mtcars, aes(x=cyls)) + geom_bar()
> #grid.gedit("xaxis::labels::label.text",just=c("center","center"))
> dev.off()
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Dr Paul Murrell
Department of Statistics
The University of Auckland
Private Bag 92019
Auckland
New Zealand
64 9 3737599 x85392
paul at stat.auckland.ac.nz
http://www.stat.auckland.ac.nz/~paul/



More information about the R-help mailing list