我需要将绘图保存为.png并同时显示绘图而不重复代码。 有一种优雅的方式吗? 使用RStudio for MAC。
我可以像以后一样工作,但我不喜欢它。
#Step1: save the plot
png("myplot.png")
#plot code
dev.off()
#Step2: to display the plot
#plot code (again!) to display it in RStudio
干杯, I.M。
答案 0 :(得分:12)
我发现以前的答案不完整。深入探讨了如何在默认的RStudio" Plots"中显示情节。窗口并将情节保存在" png"在同一时间。
如果总有一天,有人可能会遇到同样的问题,这就是如何逐行完成的:
R:>
R:> dev.list() # fresh start. no graphical devices available at this point
NULL
R:> dev.cur() # no current device at this point
null device
1
R:> dev.new() # open graphical devices
NULL
R:> dev.list() # list them
RStudioGD quartz_off_screen
2 3
R:> png("plot50.png") # open an offscreen device as png. New device should be number 4
R:> dev.list() # the list of all graphical devices includes the newly created device, number 4
RStudioGD quartz_off_screen quartz_off_screen
2 3 4
R:> dev.cur() # NOTE: the new created device(number 4) becomes "current" automatically,
quartz_off_screen # as soon as it has been created
4
R:> dev.set(which = 2) # switch back to device 2 used to display the plot in the default RStudio
# "Plots" window
RStudioGD
2
R:> dev.cur() # indeed, RstudioGD becomes the current device after the switch step from above
RStudioGD
2
R:> dev.list() # just a check on all available devices. device 4 still in the list after
# the switch
RStudioGD quartz_off_screen quartz_off_screen
2 3 4
R:> plot(c(1:100)) # plot an example. It will be displayed in "Plots" window of RStudio
R:> dev.list() # just a check on all the available devices
RStudioGD quartz_off_screen quartz_off_screen
2 3 4
R:> dev.copy(which = 4) # copies from current device(RStudioGD) to device 4. It automatically sets
quartz_off_screen # device 4 as current
4
R:> dev.cur() # indeed , device 4 is the current device
quartz_off_screen
4
R:> dev.off() # close device 4. IMPORTANT: AT THIS POINT the plot is saved as
RStudioGD # png("plot50.png") in the current working directory.
# Three actions takes place at this point, all at once:
# 1. closes device 4
# 2. save the plot as "plot50.png"
# 3. sets the de.next() (which is RStudioGD) as the current device
2
R:> dev.cur() # RStudioGD becomes current as soon as device 4 has been closed down.
RStudioGD
2
R:>
答案 1 :(得分:1)
为了增加弗拉门戈的伟大答案,这里有一个简单的版本似乎可以在RStudio中运行。假设您在RStudio中绘制了一些内容,然后想要保存同样的东西。
pdf(file = "xyz.pdf")
dev.set(which = 2)
dev.copy(which = 4)
dev.off()
我尝试重复使用dev.off(),这个工作流程看起来非常稳定。
答案 2 :(得分:0)
我找到了答案here:
如果按照上一节中的过程进行操作,则首先必须在屏幕上绘制一个图,然后重新输入命令以将图保存到文件中。 R还提供了dev.copy命令,用于将图形窗口的内容复制到文件中,而无需重新输入命令。对于大多数情节来说,一切都会好起来的,但是有时将屏幕上的内容转换为其他格式看起来并不理想。
要使用此方法,请首先以常规方式生成图形。什么时候 您对它的外观感到满意,请调用dev.copy,将其传递给 您要使用的驱动程序,要存储在其中的文件名以及其他任何文件 适用于驱动程序的参数。
他们使用dev.copy
给出的示例如下:
dev.copy(png,'myplot.png')
dev.off()