R 图形 : output to several file formats

标签 r ggplot2 graphics lattice device-driver

在许多脚本中,我首先在屏幕上开发一个图形,然后需要将其保存为具有特定高度/宽度/分辨率的多种文件格式。使用 png() , pdf() , svg() , ... 打开设备,然后 dev.off()要关闭它,我不得不将所有设备打开调用放入我的脚本中,然后将它们注释掉并一次在一台设备上重新运行代码。

我知道对于 ggplot 图形,ggsave()使这更容易。
我可以做些什么来简化 base-R 格子图形?

一个例子:

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

您可以使用文档中的更多内容。

关于R 图形 : output to several file formats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59605378/

相关文章:

r - 如何在 R 中格式化货币

r - 用虚线连接多个面的多个点

r - 避免分面ggplots中的轴刻度标签冲突

r - 按 ggplot2 geom_count 中的出现次数对点进行着色

c# - 根据鼠标拖动方向和模型中的位置旋转模型组

graphics - 如何转换亚像素精度的图像?

r - lme4:如何用随机截距指定 2 个相关性,而不在随机斜率之间添加相关性

r - 动态显示仪表板页面

r - 计数器最大频率非连续数

r - 如何读取 coplot() 图