由于可以将R图输出为PDF 或 PNG 或 SVG等,是否也可以将R图输出为多种格式 at一旦?例如,将情节导出为PDF 和 PNG 和 SVG,而无需重新计算情节?
答案 0 :(得分:0)
是的,绝对!这是代码:
library(ggplot2)
library(purrr)
data("cars")
p <- ggplot(cars, aes(speed, dist)) + geom_point()
prefix <- file.path(getwd(),'test.')
devices <- c('eps', 'ps', 'pdf', 'jpeg', 'tiff', 'png', 'bmp', 'svg', 'wmf')
walk(devices,
~ ggsave(filename = file.path(paste(prefix, .x)), device = .x))
答案 1 :(得分:0)
不使用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)
的绘图生成代码替换 - 您可能需要明确地print
ggplot对象。