【2.4】R图片的导出

SCI文章投稿最重要的莫过于图片的处理。一般杂志对图片要求:图片最低分辨率300DPI,部分杂志要求不低于600DPI,点线图及柱状图部分杂志要求达800DPI甚至1200DPI。杂志要求的分辨率是指原始图片的分辨率,经过Photoshop处理后修改图片的分辨率以达到杂志的要求通常是不可取的。以下介绍组图过程中的一些个人经验。

一.图形的两种格式:

矢量图与位图的区别矢量图形使用函数来记录图形中的颜色,尺寸等属性。物体的任何放大和缩小,都不会使图像失真和降低品质。也不会对文件的大小有影响。矢量图形表现清晰的轮廓,常用于制作一些标志图形。 矢量图只能表示有规律的线条组成的图形,如工程图、三维造型或艺术字等;对于由无规律的像素点组成的图像(风景、人物、山水),难以用数学形式表达,不宜使用矢量图格式;其次矢量图不容易制作色彩丰富的图像,绘制的图像不很真实,并且在不同的软件之间交换数据也不太方便。另外,矢量图像无法通过扫描获得,它们主要是依靠设计软件生成。矢量绘图程序定义(像数学计算)角度、圆弧、面积以及与纸张相对的空间方向,包含赋予填充和轮特征性的线框。常见的矢量图处理软件有CoreIDRAW、AutoCAD、Illustrator和FreeHand等

位图图像是很多的彩色网格来拼成一幅图像的,每个网格称为一个像素,像素都有特定的位置和颜色值。如果位图图像放大后会发现有马赛克一样的一个个像素。位图图像与矢量图像相比更容易模仿照片似的真实效果。位图图像的主要优点在于表现力强、细腻、层次多、细节多,可以十分容易的模拟出像照片一样的真实效果。由于是对图像中的像素进行编辑,所以在对图像进行拉伸、放大或缩小等到处理时,其清晰度和光滑度会受到影响。位图图像可以通过数字相机、扫描或PhotoCD获得,也可以通过其他设计软件生成

矢量图形(PDF, PostScript, SVG,AI,) 和 位图(PNG, JPEG, TIFF,bmp,jpg)

二.R中图形的几种保存方式

1 savePlot 的妙用(在R中的使用,非Rstudio)

savePlot(filename = "Rplot",
		 type = c("wmf", "emf", "png", "jpg", "jpeg", "bmp",
				  "tif", "tiff", "ps", "eps", "pdf"),
		 device = dev.cur(),
		 restoreConsole = TRUE)

#注:Types “eps” and “ps” are the same thing apart from the extension for the default filename. Similarly “wmf”/“emf”, “jpeg”/“jpg"and “tiff”/“tif”。JPEG quality is 75%, and TIFF is saved without compression。

> savePlot(filename="aa",type=c("tif"),device=dev.cur(),restoreConsole=TRUE)
Error in savePlot(filename = "aa", type = c("tif"), device = dev.cur(),  :
  can only copy from 'windows' devices

所以这个命令在Rstudio上没法运行,在在R编辑器下运行成功

2.粘贴复制(rstudio)

生成图片以后,点击copy to clipboard,调整合适的大小,然后选择copy as的类型(bitmap,metafile), 确认后,然后就可以将图片粘贴到你想要他到的地方了,得到的是矢量图

3导出高清的图

导出分辨率较高图片的命令:

tiff(filename = "test.tif",width = 15,height = 18,units ="cm",compression="lzw",bg="white",res=600)

#res设置图片分辨率,。units指定长宽的单位,px(oixeis,默认的),in(inches),cm或者mm。compression为压缩方式,lzw压缩之后图片较小。可选的方式为none,rle,zlw,jpeg,zip。

heatmap.2(data,col=redgreen(75), scale="row",key=TRUE, symkey=FALSE, trace="none", cexRow=0.5,density.info="none",labRow=FALSE,margins=c(4.5,0.5),lhei=c(2.5,10),lwid=c(2.0,4.2))
dev.off()

airo可以创建高质量的矢量图形(PDF, PostScript, SVG) 和 位图(PNG, JPEG, TIFF),同时支持在后台程序中高质量渲染!

可有两种行为: 一是打开设备并设置相关参数,然后绘图,关闭设备,ok,欣赏你的图片吧!如:

pdf(file="example.pdf", width=12, height=8) #矢量图,pdf格式
svg(file="example.svg", width=12, height=8) #矢量图,svg格式
tiff(file="example.tiff", width=12, height=8, units="in", compression="lzw", res=150) #位图,tiff格式,常用于文章投稿。

dev.off()

例如:

svg(file="plot.svg",width=12,height=8)
plot(c(1,6,3,7,6,9),type="l")
dev.off()

#这个矢量图用IE打开,发现放大也不会变模糊,这就是矢量图的好处。

一是先在X11设备上绘制图形,根据图形好坏进行细调,满意后利用dev.copy函数保存为想要的格式的文件。如:

plot(...)
abline(...)
lines()
blablabla...
dev.copy(postscript, file=”myfile.eps”, height=6, width=6, horizontal=F, onefile=F)
dev.copy(png, filename=”myfile.png”, height=600, width=800, bg=”white”)
dev.print(device=postscript, file=”yourFileName.ps”)
dev.copy2pdf(file="heatmap.pdf",out.type="pdf")
dev.off()

各种图形保存的命令

bmp(filename = "Rplotd.bmp",
	width = 480, height = 480, units = "px", pointsize = 12,
	bg = "white", res = NA, family = "", restoreConsole = TRUE,
	type = c("windows", "cairo"), antialias)

jpeg(filename = "Rplotd.jpg",
	 width = 480, height = 480, units = "px", pointsize = 12,
	 quality = 75,
	 bg = "white", res = NA, family = "", restoreConsole = TRUE,
	 type = c("windows", "cairo"), antialias)

png(filename = "Rplotd.png",
	width = 480, height = 480, units = "px", pointsize = 12,
	bg = "white", res = NA, family = "", restoreConsole = TRUE,
	type = c("windows", "cairo", "cairo-png"), antialias)
调高 DPI.

png(..., res = 300)

tiff(filename = "Rplotd.tif",
	 width = 480, height = 480, units = "px", pointsize = 12,
	 compression = c("none", "rle", "lzw", "jpeg", "zip", "lzw+p", "zip+p"),
	 bg = "white", res = NA, family = "", restoreConsole = TRUE,
	 type = c("windows", "cairo"), antialias)

4.ggsaves输出ggplot的结果

For high-quality print output, use at least 300 ppi. Figure 14-2 shows portions of the same plot at different resolutions. In this example, we’ll use 300 ppi and create a 4×4- inch PNG file:

ppi = 300
# Calculate the height and width (in pixels) for a 4x4-inch image at 300 ppi
png("myplot.png", width=4*ppi, height=4*ppi, res=ppi)
plot(mtcars$wt, mtcars$mpg)
dev.off()

或者

 ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
	# Default dimensions are in inches, but you can specify the unit
	ggsave("myplot.png", width=8, height=8, unit="cm", dpi=300)

改变字体

install.packages("extrafont")
library(extrafont)
# Find and save information about fonts installed on your system
font_import()
# List the fonts
fonts()
After the one-time setup is done, there are tasks you need to do in each R session:
library(extrafont)
# Register the fonts with R
loadfonts()

# On Windows, you may need to tell it where Ghostscript is installed
# (adjust the path to match your installation of Ghostscript)
Sys.setenv(R_GSCMD = "C:/Program Files/gs/gs9.05/bin/gswin32c.exe")
Finally, you can create a PDF file and embed fonts into it, as in Figure 14-4:
library(ggplot2)
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
	ggtitle("Title text goes here") +
	theme(text = element_text(size = 16, family="Impact"))
ggsave("myplot.pdf", width=4, height=4)
embed_fonts("myplot.pdf")

三、图片不清晰

R中生成的图片,保存为.tiff格式,有3M,在word里还是模糊

i) 一般情况下,如果需要在word中插入图片,分为两种方法:复制黏贴与插入图片菜单。同时,由于word文档往往为表述性质使用,因此并不需要分辨率很高的图片,像我个人使用都是800*600的jpg格式,单张图片尺寸保持在100k~200k之间刚好。然后如果插入图片较多,往往会造成word文档尺寸较大,不便于使用MMS工具传输,所以会使用wrod中的图片处理工具压缩文档中的所有图片。

ii) 关于图片模糊,事实上在给定显示设备参数不变的状态下会有两种情况,一种是图片分辨率太低,还有一种是图片分辨率太高。解决方法是根据你最终输出的需求(出版物,电子文档等)来调整相应输出设备分辨率参数,并把其作为模版保存下来即可,至于具体参数——你也是老坛友了就无需给出具体参数说明了。

四、服务器上批量生成图片

p = ggplot(aes(x='mpg'), data=mtcars) + geom_histogram()
print p
p.save("myplot.png")
RuntimeError: could not open display

解决办法:

matplotlib解决办法

# do this before importing pylab or pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
fig.savefig('test.png')

ggplot解决办法:

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import ggplot as gp
	test_time = [0, 2, 2, 4]
	test_value = [1, 1, 0, 0]
	p= gp.qplot(test_time, test_value)
	p.save("myplot.png")

ps: 感谢刘师兄给的建议

参考资料:

http://blog.sina.com.cn/s/blog_4be5711f01013e4z.html

http://blog.sina.cn/dpool/blog/s/blog_70281e960100vky3.html

http://cos.name/cn/topic/109475/

http://cos.name/cn/topic/111881/

http://cqu-999.appspot.com/article/247001/SCI图片处理与组图技巧

https://github.com/yhat/ggplot/blob/master/docs/how-to/Saving%20Plots%20to%20a%20File.ipynb

http://stackoverflow.com/questions/13336823/matplotlib-python-error

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn