在许多脚本中,我首先在屏幕上绘制图形,然后将其保存为具有特定高度/宽度/分辨率的几种文件格式。使用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()
图形设备是grDevices软件包的一部分。关于使用多个打开的设备的documentation可能值得一读。据我了解,存储了一个开放设备的循环阵列,但是只有当前设备处于活动状态。因此,最好打开所有所需的设备,然后用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
您可以使用的文档中还有很多内容。
您可以使用cowplot包将基础图形或点阵图形转换为ggplot2对象,然后可以通过ggsave()
保存。这并非完全安全,但适用于大多数情节。您还需要安装gridGraphics软件包才能正常工作。查看更多here.
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
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9rRXgwTkxKLnBuZyJ9” alt =“”>
# 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
由reprex package(v0.3.0)在2020-01-05创建