R 绘图:输出到多种文件格式

5
在一些脚本中,我首先在屏幕上开发一个图表,然后需要将其保存为特定高度/宽度/分辨率的多个文件格式。使用`png()`、`pdf()`、`svg()`等打开设备,然后使用`dev.off()`关闭它,我被迫把所有打开设备的调用放入我的脚本中,并逐个注释和重新运行代码。我知道对于ggplot图形,`ggsave()`使这更容易。是否有任何方法可以简化这个过程,使其适用于base-R和lattice图形呢?一个例子:
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() 
2个回答

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

文档中还有更多可供使用的内容。

在IT技术方面。请注意保留HTML标记,但不要添加任何解释或修改格式。

1
你可以使用cowplot包将基本或lattice图形转换为ggplot2对象,然后通过ggsave()保存。这并非完全可靠,但适用于大多数情况。为此,您还需要安装gridGraphics包。更多信息请参见此处
library(ggplot2)
library(cowplot)
#> 
#> ********************************************************
#> Note: As of version 1.0.0, cowplot does not change the
#>   default ggplot2 theme anymore. To recover the previous
#>   behavior, execute:
#>   theme_set(theme_cowplot())
#> ********************************************************

# define a function that emits the desired plot
p1 <- function() {
  par(
    mar = c(3, 3, 1, 1),
    mgp = c(2, 1, 0)
  )
  boxplot(mpg ~ cyl, xlab = "cyl", ylab = "mpg", data = mtcars)
}

# the plot using base graphics
p1()


# the plot converted into a ggplot2 object
p2 <- ggdraw(p1)
p2


# save in different formats
ggsave("plot.pdf", p2)
#> Saving 7 x 5 in image
ggsave("plot.png", p2)
#> Saving 7 x 5 in image
ggsave("plot.svg", p2)
#> Saving 7 x 5 in image

2020年1月5日使用reprex package(v0.3.0)创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接