脚本中的ggplot图不会显示在Rstudio中 [英] ggplot plots in scripts do not display in Rstudio

查看:2034
本文介绍了脚本中的ggplot图不会显示在Rstudio中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rstudio出现了一个奇怪的问题:如果一个脚本调用ggplot2函数来显示一个图,那么使用 Source 运行该脚本不会产生图。如果我用 Ctrl + A 选择整个脚本,那么运行当前行或选择( Ctrl + Enter ),然后显示 。同样,在控制台中输入plotting命令会产生正确的输出。



例如:

  library(ggplot2)

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

只有在粘贴到控制台时才会产生输出,而不是源代码。

还有其他的问题,但两者都没有帮助:



当脚本来源时,如何让Rstudio显示图表?我使用Rstudio 0.98.1062和R 3.1.1。解决方案

解决方案是显式调用 print()在ggplot对象上:

  library(ggplot2)

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

ggplot 函数返回类ggplot的对象; ggplot2通过重载 print 函数在类ggplot的对象上表现不同 - 而不是将它们打印到STDOUT,它创建图表。



在交互模式下一切正常,因为R假定大部分命令都通过 print()函数运行。这是为了我们的方便,并允许我们键入 rnorm(1)并获得任何可见的输出。使用运行当前选择命令( Ctrl + Enter )时,RStudio的行为就好像每个选定的行都以交互模式键入并运行一样。您可以通过在运行少数选定行后在 Console 窗格中检查您的命令历史记录来验证它。

但这种方便的模式在通过 source()读取文件时被放弃。由于此功能旨在运行(可能长且计算量大)的R脚本,因此不希望使用低优先级消息来污染STDOUT。这就是为什么默认情况下 source()只会输出错误信息。如果你想要别的东西,你必须明确地要求。


I have a strange issue with Rstudio: If a script calls ggplot2 functions to display a plot, then using Source to run the script does not produce the plots. If I select the whole script with Ctrl+A, then Run the current line or selection (Ctrl+Enter), then the plot does display. Likewise, typing plotting commands into the console produces correct output.

For example:

library(ggplot2)

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

Will only produce output if pasted into console, not if sourced.

There are other questions about this, but neither is helpful:

How can I get Rstudio to display plots when a script is sourced? I am using Rstudio 0.98.1062 and R 3.1.1.

解决方案

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.

这篇关于脚本中的ggplot图不会显示在Rstudio中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆