简体   繁体   English

R ggiraph-运行.R文件时无图

[英]R ggiraph - no plot when running .R file

How do I get the graph when executing a .R file? 执行.R文件时如何获取图形? The file ( test.r ) looks like this: 文件( 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))

I am running it with this command: 我正在使用以下命令运行它:

R < test.R --no-save

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并输入代码,则Firefox将打开并显示一个非常漂亮的图形,其中显示了所需的鼠标悬停标签。

R version 3.2.3 (2015-12-10)
x86_64-pc-linux-gnu

R generates a temporary .html file and then spawns a gvfs-open process to view that file (which in turn opens Firefox). R生成一个临时的.html文件,然后生成一个gvfs-open进程来查看该文件(依次打开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. 当您从命令行运行脚本时, R退出并清理其临时文件,然后Firefox进程才有机会完全加载。 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

A simple fix is to add Sys.sleep(5) at the end of your script. 一个简单的解决方法是在脚本末尾添加Sys.sleep(5) 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几秒钟,从而允许gvfs-open进程在浏览器窗口中完成打开临时文件的操作,然后R退出并自行清除。

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. 请注意, RSys.sleep()之后退出时仍会删除临时index.html文件,但是Firefox在内存中已经具有缓存。

EDIT: An alternative solution is to explicitly write out your interactive plot to an .html file that persists after R exits. 编辑:一种替代解决方案是将交互式绘图明确写出为.html文件,该文件在R退出后仍然存在。 You can do this by storing the result of ggiraph to a variable and then passing that to htmlwidgets::saveWidget : 您可以通过将ggiraph的结果存储到变量中,然后将其传递给htmlwidgets::saveWidget

myplot <- ggiraph(code = print(gg1))
htmlwidgets::saveWidget( myplot, "test.html" )
browseURL( "test.html" )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM