简体   繁体   中英

R: Importing vector graphics to a plot - Cannot get grImport to work

I am trying to use the grImport package ( http://cran.r-project.org/web/packages/grImport/index.html ) to import an external vector image into an R plot, eg I take this picture:

画画

and then I convert to ps using the convert of ImageMagick:

convert crashed.jpg crashed.ps

I the start R and issue the following commands:

R> library("grImport")
R> PostScriptTrace("crashed.ps", "crashed.xml")
R> myPic = readPicture("crashed.xml")
R> grid.picture(myPic)

and then according to http://cran.r-project.org/web/packages/grImport/vignettes/import.pdf the image is supposed to be displayed. But all I get is an empty plot popping up!

R> sessionInfo()
R version 3.1.3 (2015-03-09)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.3 (Yosemite)

This is a fairly old question. Given that it's still unanswered, I thought I'd share some modern tools for incorporating external graphics into R plots.

Preliminaries

Using ImageMagick or equivalent, convert the source .jpg to .pdf . On Linux, this is done using convert crashed.jpg crashed.pdf . We will also use the following base plot throughout the answer:

library( ggplot2 )
g0 <- ggplot( mtcars, aes(disp, mpg) ) + geom_point() + theme_bw()

Importing the image as a plot panel using grImport2

We first use grConvert to convert the .pdf to a .svg, which is then imported and converted to a grob object.

grConvert::convertPicture( "crashed.pdf", "crashed.svg" )
p <- grImport2::readPicture( "crashed.svg" )
g <- grImport2::pictureGrob( p )
gridExtra::grid.arrange( g0, g, nrow=1 )

在此处输入图片说明

Overlaying the image on top of an existing plot using cowplot

Unlike the above, this solution works directly with the .jpg:

## Ensure magick is installed for draw_image()
if(!require("magick")) install.packages( "magick" )
cowplot::ggdraw(g0) + cowplot::draw_image("crashed.jpg", x=0.25, y=0.25, scale=0.25)

在此处输入图片说明

Using the image as a plot element with the help of egg

This approach also works directly with the .jpg. We load the image and populate a new column in mtcars with the resulting object. The column can then be provided to geom_custom() in a standard ggplot fashion:

mtcars$img <- list(jpeg::readJPEG( "crashed.jpg" ))
g0 + egg::geom_custom( data=mtcars, aes(data=img), grob_fun=grid::rasterGrob,
                      fun_params = list(height=unit(1,"lines")) )

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM