Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print plot(lm(y~x) in R using png() and dev.off()

Tags:

linux

plot

r

png

I'd like to print-to-file the regression diagnostic charts that R produces when you plot() the fit of a linear model. There are four, and they interrupt execution with

Hit <Return> to see next plot:
Hit <Return> to see next plot: 
Hit <Return> to see next plot: 
Hit <Return> to see next plot: 

So, the following code, which normally does work, did not:

png('Filename.png', width=mywidth, height=myheight, units='in', res=300)
plot(lm(y~x)
dev.off()

in that I still had to hit enter each time, and it isn't clear this would have properly subplotted, or named each plot as a different file.

How can I capture these diagnostic images directly printed to disk? If it matters, I'm on a linux machine.

like image 870
Mittenchops Avatar asked Dec 20 '22 22:12

Mittenchops


1 Answers

A couple of options are, using the following dummy data

set.seed(42)
x <- rnorm(100)
y <- 3.4 + (0.5 * x) + rnorm(100)

Use the ask argument and set it to FALSE:

png('Filename%03d.png', width=6, height=6, units='in', res=300)
plot(lm(y~x), ask = FALSE)
dev.off()

Note that we have to use %03d to add a number to "Filename" so we have "Filename001.png" etc. for the four images. See ?plot.lm for the details of ask and ?png for the notation in the filename.

Alternatively, set up the plotting device with 4 panels and plot the model:

png("Filename_all.png", width=6, height=6, units='in', res=300)
layout(matrix(1:4, ncol = 2))
plot(lm(y~x))
layout(1)
dev.off()
like image 188
Gavin Simpson Avatar answered Dec 24 '22 02:12

Gavin Simpson