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.
Mirosław Zalewski Nov 29 '14 at 11:27 2014-11-29 11:27
source share