【问题标题】:How to save plots automatically to png?如何将绘图自动保存为png?
【发布时间】:2018-12-06 14:50:01
【问题描述】:

是否可以通过以下方式将绘图自动保存到png格式的文件夹中?

  1. 每次调用plot.new() 时都会创建一个新的png 文件
  2. 文件会在每次图形更新时更新(例如,当调用points()lines()rect() 时),因此每当更新绘图时,文件也会更新(无需关闭设备dev.off())

如果可能的话,下面的代码应该可以正常工作:

plot(rnorm(100))
# create a new png file (e.g. plot-1.png) and the graphics is output to the file

plot(rnorm(100))
# create a new png file (e.g. plot-2.png) and the graphics is output to the file
abline(h = 0, col = "red")
# then the line is output to the file

这样做的动机是为了避免 X11/Quartz 转发(它们不能很好地与 screen/tmux 配合使用,因为当用户从其他地方附加会话时图形会丢失),并避免看起来似乎是 xpra很少有人支持它(导致 Ubuntu 16.04 卡在登录屏幕,请参阅 https://askubuntu.com/questions/930161/ubuntu-16-04-2-cannot-login-after-installing-xpra?noredirect=1#comment1661998_930161)。

这很像 RStudio Server 处理 R 图形的方式(参见https://github.com/rstudio/rstudio/tree/master/src/cpp/r/session/graphics 的源代码)。我想知道是否有更简单的方法来实现这一点(最好不要从头开始重写图形设备)?

【问题讨论】:

  • 在绘图之前,调用函数png。见help("png")。完成后,dev.off()
  • 查看rmote,这是我通过 ssh/emacs/ess 控制 R 并想查看我的绘图时定期使用的工具。
  • @RuiBarradas 我提到这里不需要png(...); plot(...); dev.off(),因为我想捕获在会话中创建的所有 图形,而不会将我所有的绘图代码更改为这种样式。期望的结果是,对于 RStudio 用户,绘图很好,但对于终端用户(例如 emacs+ess),绘图应自动重定向到 png 文件,无论我在哪里附加到屏幕/tmux 会话,这些文件都会保留。

标签: r x11 graphic rstudio-server


【解决方案1】:

我会快速总结一下我如何使用rmote,尽管 github 页面有更多信息。

  1. ssh -L 4321:localhost:4321 remoteuser@remotehost
  2. tmux(或tmux attach,如果已经开始)
  3. emacs,使用 ESS 启动 R
  4. 一次,让事情开始:

    library(rmote)
    start_rmote(server_dir="path/to/save/pngs")
    
  5. 制作一些绘图,将您的本地网络浏览器指向http://127.0.0.1:4321。 (最初它会显示一个目录列表,但是一旦绘图开始它应该自动刷新。)

    plot(1:10, type='l')
    plot_done() # required for base-graphics
    plot(2:20)
    plot_done()
    library(ggplot2)
    ggplot(mtcars, aes(mpg, disp)) + geom_point() # no plot_done() required for ggplot2
    
  6. 从 tmux/ssh 断开连接。 (由于隧道关闭,网页可能会失败。)

  7. 重新连接,ssh -L 4321:localhost:4321 remoteuser@remotehosttmux attach
  8. 刷新浏览器,所有绘图可用(仍保留完整历史记录)
  9. 完成后,stop_rmote()。所有绘图都保存在path/to/save/pngs/plots/

奖励:如果您使用同一目录执行start_rmote(...),则将提供相同的情节历史记录。因此,如果您必须重新启动 R 会话,则不会丢失任何内容。 (我还没有测试过它,但也许它可以与同时的 R 会话一起工作......)

编辑

我经常更改绘图的大小,部分原因是为了填满浏览器的屏幕,但有时是为了设置报告的特定文件大小或复制不同的屏幕限制。

options(rmote_device = list(type="png", retina=TRUE, width=1024, height=768))

参考:https://github.com/cloudyr/rmote/blob/ee13936806cc1be5b2f95b70b33af374331ae2dc/man/rmote_device.Rd

EDIT 2:我想我应该注意到,虽然可能没有充分利用 rmote 的功能,但确实可以将其 用于目的使用大多数绘图方法生成自动 PNG。您不必连接到 127.0.0.1:4321 即可实现自动保存 PNG 的好处。

【讨论】:

  • 谢谢! plot_done() 是我提到的不想要的代码,这使得脚本对 RStudio 用户不可移植。
  • ...尽管有everyone's wishbest intentions,它仍然是R 基础图形作品所必需的。在基本图形中,对预期图形的每次添加都会导致画布发生更改:plot(...);lines(...);text(...)。在什么时候“完成”?使用ggplot2(例如),默认方法会一次性绘制所有内容,尽管您可以绕过它。对于基本图形,情况并非如此,因此当预期的绘图完成时,完全不清楚
  • 我怀疑有可能保存这些步骤中的每一个。您是否联系过 RStudio 询问他们是如何做到的?也许 JJ 可以为您(以及其他人,例如 rmote)提供有关如何使用基本图形解决 R 的“-isms”的指导。
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 2015-06-24
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2019-11-11
  • 2018-11-06
相关资源
最近更新 更多