将R绘图导出为多种格式 [英] Export R plot to multiple formats
问题描述
由于可以将R绘图导出为PDF 或 PNG 或 SVG等,因此也可以将R绘图导出为多种格式
Since it is possible to export R plots to PDF or PNG or SVG etc., is it also possible to export an R plot to multiple formats at once? E.g., export a plot to PDF and PNG and SVG without recalculating the plot?
推荐答案
在不使用ggplot2
和其他软件包的情况下,这是两个替代解决方案.
Without using ggplot2
and other packages, here are two alternative solutions.
-
创建一个函数,该函数使用指定的设备生成图形并对其进行
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()
}
第二种方法可能有点棘手,因为它需要非标准评估.但是它也可以正常工作.两种方法都可以在其他包括ggplot2
的绘图系统上工作,只需将上面的plot(x, y)
的绘图生成代码替换为-尽管您可能需要显式地print
ggplot对象.
The second method may be a little tricky because it requires non-standard evaluation. Yet it works as well. Both methods work on other plotting systems including ggplot2
simply by substituting the plot-generating codes for the plot(x, y)
above - you probably need to print
the ggplot object explicitly though.
这篇关于将R绘图导出为多种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!