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.
To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.
Save the chart to a file by hovering over the export button in the axes toolbar and selecting the first item in the drop-down list. MATLAB displays the Save As dialog box with the file type options.
Matplotlib plots can be saved as image files using the plt. savefig() function.
There are two closely-related questions, and an answer for each.
To save a plot, you need to do the following:
png()
, bmp()
, pdf()
or similardev.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
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
.
If you want to keep seeing the plot in R, another option is to use dev.copy
:
X11 () plot (x,y) dev.copy(jpeg,filename="plot.jpg"); dev.off ();
If you reach a clutter of too many plot windows in R, use graphics.off()
to close all of the plot windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With