由于可以将 R 图导出为 PDF 或 PNG 或 SVG 等,是否也可以一次将 R 图导出为多种格式?例如,在不重新计算绘图的情况下将绘图导出为 PDF、PNG 和 SVG?
最佳答案
在不使用 ggplot2
和其他包的情况下,这里有两个替代解决方案。
sapply
# Create pseudo-data
x <- 1:10
y <- x + rnorm(10)
# Create the function plotting with specified device
plot_in_dev <- function(device) {
do.call(
device,
args = list(paste("plot", device, sep = ".")) # You may change your filename
)
plot(x, y) # Your plotting code here
dev.off()
}
wanted_devices <- c("png", "pdf", "svg")
sapply(wanted_devices, plot_in_dev)
dev.copy
# With the same pseudo-data
# Plot on the screen first
plot(x, y)
# Loop over all devices and copy the plot there
for (device in wanted_devices) {
dev.copy(
eval(parse(text = device)),
paste("plot", device, sep = ".") # You may change your filename
)
dev.off()
}
第二种方法可能有点棘手,因为它需要 non-standard evaluation 。然而它也能工作。这两种方法都适用于包括
ggplot2
在内的其他绘图系统,只需将绘图生成代码替换为上面的 plot(x, y)
- 您可能需要显式地对 ggplot 对象进行 print
。
关于r - 将 R 图导出为多种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132169/