R ggiraph - 运行 .R 文件时没有绘图 [英] R ggiraph - no plot when running .R file
问题描述
如何在执行 .R 文件时获取图形?文件 (test.r
) 如下所示:
How do I get the graph when executing a .R file? The file (test.r
) looks like this:
library(ggplot2)
library(ggiraph)
gg <- ggplot(data = mtcars, aes(x = mpg, y = wt, color = factor(cyl)))
gg1 <- gg + geom_point_interactive(aes(tooltip = gear), size = 5)
ggiraph(code = print(gg1))
我用这个命令运行它:
R < test.R --no-save
但是什么也没发生.如果我只是从命令行运行 R 并逐行输入代码,Firefox 将打开并显示一个非常漂亮的图形,其中显示了想要的鼠标悬停标签.
But nothing happens. If I just run R from the command line and enter the code line-by-line Firefox opens and shows a really nice graph with the wanted mouse-over label showing.
R version 3.2.3 (2015-12-10)
x86_64-pc-linux-gnu
推荐答案
R
生成一个临时 .html 文件,然后生成一个 gvfs-open
进程来查看该文件(这又会打开 Firefox).当您从命令行运行脚本时,R
会在 Firefox 进程有机会完全加载之前退出并清理其临时文件.您可以通过执行此操作来查看此效果
R
generates a temporary .html file and then spawns a gvfs-open
process to view that file (which in turn opens Firefox). When you are running your script from the command line, R
exits and cleans up its temporary files before Firefox process has a chance to fully load. You can see this in effect by doing
$ R -q --interactive < test.R
> library(ggplot2)
> library(ggiraph)
> gg <- ggplot(data = mtcars, aes(x = mpg, y = wt, color = factor(cyl)))
> gg1 <- gg + geom_point_interactive(aes(tooltip = gear), size = 5)
> ggiraph(code = print(gg1))
Save workspace image? [y/n/c]:
gvfs-open: /tmp/RtmpPxtiZi/viewhtml3814550ff070/index.html: error opening location:
Error when getting information for file '/tmp/RtmpPxtiZi/viewhtml3814550ff070/index.html': No such file or directory
一个简单的解决方法是在脚本末尾添加 Sys.sleep(5)
.这会暂停 R
几秒钟,允许 gvfs-open
进程在 R
退出并清理之前完成在浏览器窗口中打开临时文件自己起来.
A simple fix is to add Sys.sleep(5)
at the end of your script. This pauses R
for a few seconds, allowing gvfs-open
process to finish opening your temporary file in a browser window, before R
exits and cleans up after itself.
注意 R
在 Sys.sleep()
之后退出时仍会删除临时的 index.html
文件,但 Firefox 已经在内存中有缓存.
Note that R
will still remove the temporary index.html
file when it exits after Sys.sleep()
, but Firefox will already have a cache in memory.
另一种解决方案是将您的交互式绘图明确写出到一个 .html 文件中,该文件在 R
退出后仍然存在.您可以通过将 ggiraph
的结果存储到一个变量然后将其传递给 htmlwidgets::saveWidget
来实现:
An alternative solution is to explicitly write out your interactive plot to an .html file that persists after R
exits. You can do this by storing the result of ggiraph
to a variable and then passing that to htmlwidgets::saveWidget
:
myplot <- ggiraph(code = print(gg1))
htmlwidgets::saveWidget( myplot, "test.html" )
browseURL( "test.html" )
这篇关于R ggiraph - 运行 .R 文件时没有绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!