Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

r - Combining vector and bitmap graphics in a pdf

When plotting images or heatmaps to pdfs as in the example below they are saved as vector objects where every pixel in the image or cell in the heatmap is represented by a square. Even at modest resolutions this results in unnecessarily large files that also renders uglily on some devices. Is there a way to make R save only the image area as a png or jpg embedded in the pdf but keep text, axes, anotations etc as vector graphics?

I'm asking since I am often printing R graphics, sometimes on large posters, and would like to combine the best of the two worlds. Of course I could save the entire figure as a high resolution png but that would not be as elegant, or combine it manually e.g. in Inkscape but it is quite tedious.

my.func <- function(x, y) x %*% t(y)
pdf(file="myPlot.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100))
dev.off()

The figure generated by the above code

Thanks for your time, ideas and hopefully solutions!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use ?rasterImage, or more conveniently in recent versions image with option useRaster = TRUE.

That will dramatically reduce the size of the file.

my.func <- function(x, y) x %*% t(y)
pdf(file="image.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100))
dev.off()

pdf(file="rasterImage.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100), useRaster = TRUE)
dev.off()

file.info("image.pdf")$size

file.info("rasterImage.pdf")$size

image.pdf: 813229 bytes

rasterImage.pdf 16511 bytes

See more details about the new features here:

http://developer.r-project.org/Raster/raster-RFC.html

http://journal.r-project.org/archive/2011-1/RJournal_2011-1_Murrell.pdf


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...