由于R语言中的图表可以导出为PDF、PNG或SVG等格式,是否也可以将一个图表同时导出为多个格式呢?例如,将一个图表导出为PDF、PNG和SVG格式,而无需重新计算该图表。
在不使用ggplot2
和其他包的情况下,这里提供了两种替代方案。
Create a function generating a plot with specified device and sapply
it
# 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)
Use the built-in function 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 对象。是的,绝对没问题!这是代码:
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))
ggplot2
包。 - Rui Barradasdev.copy
,根据它的文档,它“将当前设备的图形内容复制到指定的设备”,即绘图不会重新计算,而是被复制。另一方面,sapply
是一个在C级别进行迭代的函数(你可以在这里找到相关讨论:https://dev59.com/yV4b5IYBdhLWcg3wiSPV)。你可能称之为“重新计算”,但对于相同的任务,它通常比`for`循环快得多。 - ytu