Solution:
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. It can be done by an extra dev.off() when plotting to a file-graphics device. This may happen if you paste in a mult-line plotting command that has a dev,off() at the end of it but errors out at the opening of the external device however then has hte dev.off() on a separate line so it accidentally closes the interactive device).
Some R implementations will start up a screen graphics device open automatically, however 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. At the time I get that error I issue plot.new()
and if I don't see a plot window, I issue quartz()
as well. So, then start over from the beginning with a new plot(., ., ...)
command and any further additions to that plot screen image.
In my instance, I was trying to call plot(x, y)
and lines(x, predict(yx.lm), col="red")
in two separate chunks in R markdown file. It worked without problems when running chunk by chunk, however the corresponding document wouldn't knit. Since I moved all plotting calls within one chunk, problem was resolved.
In newbie terms : At the time you call plot()
, the graph window gets the focus and you cannot enter further commands into R. That is the time when you conclude that you must close the graph window to return to R. But, some commands, like identify()
, act on open/active graph windows. When identify()
cannot find an open/active graph window, it gives this error message.
Nevertheless, you can simply click on the R window without closing the graph window. After you can type more commands at the R prompt, like identify()
etc.
In case someone is using print
function (for example, with mtext), then firstly depict a null plot:
plot(0,type='n',axes=FALSE,ann=FALSE)
and then print with newpage = F
print(data, newpage = F)
In base plotting, you start a plot by calling plot
or a similar command which generates a plot, which you can then add to with functions like lines
. For example, to plot a polynomial regression of mtcars,
model <- lm(mpg ~ poly(hp, 2), mtcars) # make a model
domain <- seq(min(mtcars$hp), max(mtcars$hp)) # define a vector of x values to feed into model
plot(mpg ~ hp, mtcars) # plot points
lines(domain, predict(model, newdata = data.frame(hp = domain))) # add regression line, using `predict` to generate y-values
abline
is a simplified version of lines
that only plots straight lines, and which has a method for plotting simple lm
objects.
For example, in the examples at the bottom of ?abline
,
z <- lm(dist ~ speed, data = cars)
plot(cars)
abline(z) # equivalent to abline(reg = z) or
abline(coef = coef(z))