Question

I'm trying to integrate some graph generation in my python pipeline by using rpy2. The same PDF generated inside of R, apparently doesn't work inside of rpy2. This simple script will make a readable PDF file:

#!/usr/bin/env R
library(ggplot2)
library(datasets)
p = ggplot(mtcars, aes(wt, mpg)) + xlab('Weight (lb/1000)') + ylab('Miles/(US) gallon')
pdf(file='mtcars.pdf')
p + geom_point(aes(colour=factor(cyl)))
dev.off()

While the equivalent python code produces a 4 KB file which is not readable by any PDF reader:

#!/usr/bin/env python
from rpy2 import robjects as ro
ro.r("library(ggplot2)")
ro.r("library(datasets)")
ro.r("p = ggplot(mtcars, aes(wt, mpg)) + xlab('Weight (lb/1000)') + ylab('Miles/(US) gallon')")
ro.r("pdf(file='mtcars.pdf')")
ro.r("p + geom_point(aes(colour=factor(cyl)))")
ro.r("dev.off()")

I'm using:

* Python 2.7.3
* R 2.15.2
* rpy2 2.3.6
* ggplot2 0.9.3.1

Any ideas why this is happening ? Help greatly appreciated.

Was it helpful?

Solution

Any ideas why this is happening ? Help greatly appreciated.

The ggplot figure is never plotted. In interactive R, returning something to the console will print() it (and in the case of ggplot objects, they are plotted). You'll have to call print() explicitly.

You may also want to check the rpy2 documentation for ggplot2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top