Ggplot graphs in scripts are not displayed in Rstudio

I have a strange problem with Rstudio: if a script calls ggplot2 functions to display a graph, then using the source to run the script does not produce graphs. If I select the whole script using Ctrl+A , then run the current line or selection ( Ctrl+Enter ), then the graph will be displayed. Similarly, entering commands into the console gives the correct result.

For example:

 library(ggplot2) p = ggplot(mtcars, aes(wt, mpg)) p + geom_point() 

It will produce the result only when pasted into the console, and not in the source file.

There are other questions about this, but they are not helpful:

  • The ggplot2 ggsave function causes the graphics device to not display graphics. It falsely claims that the problem is fixed in newer versions, but this is not so.
  • RStudio - ggplot does not save the first graph when printing and saving several graphs in a script , it was closed as a duplicate, but not only this is not a duplicate, but the workaround dev.off() does not work (" Error in dev.off() : cannot shut down device 1 (the null device) ")

How can I get Rstudio to display graphs when getting a script? I am using Rstudio 0.98.1062 and R 3.1.1.

+60
r rstudio ggplot2
30 Oct '14 at 2:04 on
source share
3 answers

I recently came across this question and realized that the most modern way is to call show(p) after creating the plot.

0
Jan 29 '19 at 19:21
source share

The solution is to explicitly call print() on the ggplot object:

 library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) p <- p + geom_point() print(p) 
Function

ggplot returns an object of class ggplot; ggplot2 works by overloading the print function to behave differently on objects of the ggplot class - instead of printing them in STDOUT, it creates a diagram.

Everything works well interactively because R assumes that most commands are executed through the print() function. This is for our convenience and allows you to enter rnorm(1) and get a visible result. When the current current selection command is used ( Ctrl+Enter ), RStudio behaves as if each selected line was entered interactively and started. You can verify this by checking the history of commands in the Console after running a few selected lines.

But this convenient mode is abandoned when the file is read by source() . Since this function is designed to run (potentially long and computationally expensive) R-scripts, it is undesirable to pollute STDOUT with low priority messages. Therefore, by default, source() only displays an error message. If you need anything else, you should explicitly ask about it.

+96
Nov 29 '14 at 11:27
source share

although this is a rather old question. I had the same problem and found a quick solution if you want to use the "source" button in the R studio editing window.

you can simply turn on the “source with echo” (Ctrl + Shift + Enter), and the graph shows as expected

+14
Sep 30 '16 at 10:28
source share



All Articles