Can't add to plots in R Markdown

I am new to R and RStudio so I was hoping someone here could help me.

I'm trying to add to plots in R Markdown (e.g. abline(), rug(), etc...) but whenever I try to execute these commands, I get the error message: plot.new() has not been called. Obviously, I looked up plot.new() and tried to call it and frame() but I still get the same error message. For whatever reason, I can execute these commands in script (on the console) but it only seems to be an issue in Markdown.

Has anyone else experienced similar issues or know how to resolve this? I've already unstalled and reinstalled both R and RStudio but to no avail.

Thank you in advance.

1 Like

Could you post a full snippet of the code you're using to plot the figure?

This SO answer might be helpful to you as well:

1 Like

It would help if you created a short reprex to show exactly when you are seeing the problem. However, it seems likely that you are calling the functions that add to existing plots in a different chunk than the plot was created. When you go to a new chunk, the previous plot is no longer "active".

You may be able to accomplish what you want by telling knitr to include low-level changes to plots in the output with fig.keep='all'. For example:

```{r pressure, echo=TRUE, fig.keep='all'}
plot(pressure)
abline(0, 1)
``` # Close chunk

That chunk will produce a new graph for each line of the program.

1 Like

Sure,

plot.new()
frame()
data(father.son)
lmfs <- lm(father.son$fheight ~ father.son$sheight, data=father.son)
plot(father.son$fheight,father.son$sheight)
abline(65,65)
plot(pressure)
abline(0,1)

Both of these codes produced the error: 'Error int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : plot.new has not been called yet'

Here are two sets of code that produced the same error message:

plot.new()
frame()
data(father.son)
lmfs <- lm(father.son$fheight ~ father.son$sheight, data=father.son)
plot(father.son$fheight,father.son$sheight)
abline(65,65)
plot(pressure)
abline(0,1)

The error message is ‘Error int_abline(a = a, b = b, h = h, v = v, untf = untf, …) : plot.new has not been called yet’

Thank you for the response

Mara, Thank you for the response!

This is from :princess: @mara (she ran out of replies):

So, you'll get a different result based on whether you're running each line individually, versus as a chunk. I made this little gif to show the difference. If you execute

plot(pressure)

and _then

abline(0,1)

you will get an error. You need to run the whole chunk, which you can do either by using the keyboard shortcut ⇧⌘↩, or by using the run chunk in the dropdown in RStudio (see in gif)

7 Likes

https://stackoverflow.com/questions/40938561/plot-new-has-not-been-called-yet-error-in-rmarkdown-rstudio-1-0-44?rq=1

{plot(seq(1,10,1))
 abline(a=0,b=1)}

1 Like