plot.new has not been called yet
Why does this happen?
plot(x,y)
yx.lm <- lm(y ~ x)
lines(x, predict(yx.lm), col="red")
Error in
plot.xy(xy.coords(x, y), type = type, ...)
:plot.new
has not been called yet
Some action, very possibly not represented in the visible code, has closed the interactive screen device.
It could be done either by a "click" on a close-button, or it could also be done by an extra dev.off() when plotting to a file-graphics device. (The second possibility might happen if you paste in a multi-line plotting command that has a dev.off()
at the end of it, but had errored out at the opening of the external device. So the dangling dev.off()
on a separate line accidentally closes the interactive device).
Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it.
On Windows that might be window()
; on a Mac, quartz()
; and on a Linux box, x11()
. You also may need to issue a plot.new()
command. I just follow orders. When I get that error I issue plot.new()
and if I don't see a plot window, I issue quartz()
as well. I then start over from the beginning with a new plot(., ., ...)
command and any further additions to that plot screen image.
In my case, I was trying to call plot(x, y)
and lines(x, predict(yx.lm), col="red")
in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.