Rstudio 中不显示脚本中的 ggplot 图 [英] ggplot plots in scripts do not display in Rstudio
问题描述
Rstudio 有一个奇怪的问题:如果脚本调用 ggplot2 函数来显示绘图,则使用 Source 运行脚本不会生成绘图.如果我使用 Ctrl+A
选择整个脚本,然后 运行当前行或选择 (Ctrl+Enter
),然后绘制 确实 显示.同样,在控制台中输入绘图命令会产生正确的输出.
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.
例如:
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:
- ggplot2 ggsave 函数导致图形设备不显示绘图 错误地声称该问题已在较新版本中得到解决,但实际上并没有.
- RStudio - 在脚本中打印和保存多个绘图时 ggplot 未保存第一个绘图 已作为重复项关闭,但它不仅不是重复的,而且
dev.off()
解决方法不起作用(dev.off() 中的错误:无法关闭设备 1(空设备)
")
- ggplot2 ggsave function causes graphics device to not display plots falsely claims the issue is fixed in newer versions, it has not.
- RStudio - ggplot not saving first plot when printing and saving multiple plots in a script was closed as a duplicate, yet not only is it not a duplicate, but the
dev.off()
workaround doesn't work ("Error in dev.off() : cannot shut down device 1 (the null device)
")
如何在获取脚本时让 Rstudio 显示绘图?我使用的是 Rstudio 0.98.1062 和 R 3.1.1.
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.
推荐答案
我最近遇到了这个问题,并意识到最新的方法是在创建情节后调用 show(p)
.
I recently happened on this question and realized that the most up to date way is to call show(p)
after creating the plot.
这篇关于Rstudio 中不显示脚本中的 ggplot 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!