问题
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))
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 version 3.2.3 (2015-12-10)
x86_64-pc-linux-gnu
回答1:
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
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.
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.
EDIT: 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" )
来源:https://stackoverflow.com/questions/48889846/r-ggiraph-no-plot-when-running-r-file