如何将绘图保存为磁盘上的图像? [英] How to save a plot as image on the disk?
问题描述
我使用R.绘制简单的线性回归。
我想将图像保存为PNG或JPEG,是否可以自动执行此操作? (通过代码)
有两个不同的问题:首先,我已经在看我的显示器上的情节,我想保存它。其次,我还没有生成这个图,但是当我执行我的绘图代码时,我想直接将它保存到磁盘中。
<有两个密切相关的问题,每个问题都有答案。
1。未来我的脚本中会生成一个图像,我该如何将它保存到磁盘?
要保存图,您需要执行以下操作:
$ b
- 使用
png()
,bmp()
,pdf()
或类似的元素
- 绘制您的模型
- 使用
dev.off()
关闭设备。绘制到 png
文件:
fit< - lm(一些〜模型)
png(文件名=your / file / location / name.png)
图(适合)
dev.off()
在(组合)帮助页面描述图形格式?png
,?bmp
,?jpeg
和?tiff
以及单独的帮助页面?pdf
。
请注意,图像可能看起来不同磁盘到直接绘制到屏幕上的同一个绘图,例如,如果您已经调整了scr的大小een window。
请注意,如果您的图是由格
或 ggplot2
您必须明确地打印该图。看到这个答案更详细地解释了这一点,并链接到R FAQ: ggplot的qplot不会在货源上执行
2。我正在查看屏幕上的情节,我想将它'原样'复制到磁盘。
dev .print(pdf,'filename.pdf')
这应该完全复制图像,尊重任何大小调整你已经完成了交互式窗口。在这个答案的第一部分中,您可以用其他文件类型替换 pdf
,例如 png
。
I plot a simple linear regression using R. I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)
There are two different questions: First, I am already looking at the plot on my monitor and I would like to save it as is. Second, I have not yet generated the plot, but I would like to directly save it to disk when I execute my plotting code.
There are two closely-related questions, and an answer for each.
1. An image will be generated in future in my script, how do I save it to disk?
To save a plot, you need to do the following:
- Open a device, using
png()
,bmp()
,pdf()
or similar - Plot your model
- Close the device using
dev.off()
Some example code for saving the plot to a png
file:
fit <- lm(some ~ model)
png(filename="your/file/location/name.png")
plot(fit)
dev.off()
This is described in the (combined) help page for the graphical formats ?png
, ?bmp
, ?jpeg
and ?tiff
as well as in the separate help page for ?pdf
.
Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.
Note that if your plot is made by either lattice
or ggplot2
you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing
2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.
dev.print(pdf, 'filename.pdf')
This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace pdf
with other filetypes such as png
.
这篇关于如何将绘图保存为磁盘上的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!