脚本中的 ggplot 图在 Rstudio 不会显示

我对 RStudio 有一个奇怪的问题: 如果一个脚本调用 ggplot2函数来显示一个绘图,那么使用 来源来运行这个脚本不会产生绘图。如果我选择整个脚本与 Ctrl+A,然后 运行当前行或选定内容(Ctrl+Enter) ,然后情节 是的显示。同样,在控制台中键入绘图命令也会产生正确的输出。

例如:

library(ggplot2)


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

将只产生输出,如果粘贴到控制台,而不是如果来源。

关于这一点还有其他问题,但都没有帮助:

当脚本来源时,如何让 RStudio 显示图表?我正在使用 RStudio 0.98.1062和 R 3.1。

118487 次浏览

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

library(ggplot2)


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

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

Everything is working well in interactive mode, because R assumes that most of commands are run through print() function. This is for our convenience and allows us to type rnorm(1) and get any visible output. When Run current selection command is used (Ctrl+Enter), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console pane after running few selected lines.

But this convenient mode is abandoned when file is read by source(). Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source() by default will output only error message. If you want anything else, you have to explicitly ask for that.

though it's a quite old question. I had the same problem and found a quick solution, if you want to use "source" button on R studio edit box.

you can simply turn on "source with echo" (Ctrl + Shift + Enter) and the plot shows as expected

I recently happened on this question and realized that the most up to date way is to call show(p) after creating the plot.

I found this question when searching a similar problem (plots not showing up in RStudio). I was trying to troubleshoot a complicated ggplot2 block by running it in parts, but couldn't get anything to show up in the plot window.

Reason: the tiff() function I opened earlier had not closed.

Solution: I ran dev.off() a few times until all my earlier tiff() functions completed, then I was able to create plots in RStudio and view the results in the plot window.

Another option is simply using plot(). When clicking on "Source" in Rstudio, it show the plot in the window like this:

library(ggplot2)


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


# This pops when clicking on Source
source("~/.active-rstudio-document")

Output:

enter image description here