R 图形:输出为多种文件格式

use*_*089 5 graphics r device-driver ggplot2 lattice

在许多脚本中,我首先在屏幕上开发一个图形,然后需要将其保存为具有特定高度/宽度/分辨率的多种文件格式。使用png(), pdf(), svg(), ... 打开一个设备,然后dev.off()关闭它,我被迫将所有设备打开调用放入我的脚本中并将它们注释掉并一次一个设备重新运行代码。

我知道对于 ggplot 图形,ggsave()使这更容易。对于base-R点阵图形,我可以做些什么来简化它?

一个例子:

png(filename="myplot.png", width=6, height=5, res=300, units="in")
# svg(filename="myplot.svg", width=6, height=5)
# pdf(filename="myplot.pdf", width=6, height=5)

op <- par()  # set graphics parameters
plot()       # do the plot
par(op)
dev.off() 
Run Code Online (Sandbox Code Playgroud)

Con*_* M. 2

图形设备是 grDevices 包的一部分。有关使用多个开放设备的文档可能值得一读。据我了解,存储了打开设备的循环数组,但只有当前设备处于活动状态。因此,打开所有所需的设备,然后循环使用它们dev.list()可能是最好的选择。

# data for sample plot
x <- 1:5
y <- 5:1

# open devices
svg(filename="myplot.svg", width=6, height=5)
png(filename="myplot.png", width=6, height=5, res=300, units="in")
pdf()

# devices assigned an index that can be used to call them
dev.list()
svg png pdf 
  2   3   4 

# loop through devices, not sure how to do this without calling plot() each time
# only dev.cur turned off and dev.next becomes dev.cur
for(d in dev.list()){plot(x,y); dev.off()} 

# check that graphics device has returned to default null device
dev.cur()
null device 
      1 
dev.list()
NULL

file.exists("myplot.svg")
[1] TRUE
file.exists("myplot.png")
[1] TRUE
file.exists("Rplots.pdf") # default name since none specified in creating pdf device
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

文档中还有很多内容可供您使用。