2
votes

I am able to create a dynamic 3D scatter plot using rgl and knitr, but the legend created by the legend3d is missing. I guess it may be related to the implementation of hook_webgl. Any idea? Thank you.

Here are the code I used to create the 3D scatter plot:

```{r fig1, webgl=TRUE, fig.width=10 , fig.height = 10}
  library(knitr)
  library(rgl)
  knit_hooks$set(webgl = hook_webgl)

  x <- sort(rnorm(1000))
  y <- rnorm(1000)
  z <- rnorm(1000) + atan2(x,y)
  plot3d(x, y, z, col=rep(1:2,each=500))
  legend3d("topright",legend=c("Type 1","Type 2"), pch=16, col=1:2)
```

My session info:

R version 3.1.3 (2015-03-09)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows Server 2008 R2 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base     

other attached packages:
[1] knitr_1.11    rgl_0.95.1441 dplyr_0.4.3  

loaded via a namespace (and not attached):
 [1] assertthat_0.1  DBI_0.3.1       digest_0.6.8    evaluate_0.8   
 [5] formatR_1.2.1   highr_0.5.1     htmltools_0.3   lazyeval_0.1.10
 [9] magrittr_1.5    parallel_3.1.3  R6_2.1.2        Rcpp_0.12.3    
[13] rmarkdown_0.9.5 stringi_0.5-5   stringr_1.0.0   tools_3.1.3    
[17] yaml_2.1.13   
1

1 Answers

3
votes

Looks like a bug in the rglwidget code; I'll look into it.

I recommend a few changes to your programming style. These won't help with this bug, but may save you problems later:

  • Use the setupKnitr() function rather than setting the knitr hook yourself. The link to knitr is likely to change, but setupKnitr() will protect you from problems.

  • Rather than saying webgl=TRUE in the chunk options, make a call to the rglwidget::rglwidget() function when you want to draw the plot. I'm hoping to make this call unnecessary in the future (more like what happens with regular plots), but for now it's the better tested way to do things.

  • Update your R. Current version is 3.2.3, with 3.2.4 due quite soon.

  • Use rgl and rglwidget from R-forge. They are newer than the CRAN versions, and have several bug fixes. Hopefully soon they'll have the legend bug fix too.

Added later:

This wasn't so much a bug as something that wasn't implemented. Now it is, if you use rgl version 0.95.1456 and rglwidget version 0.1.1456, both available from R-forge. Not much testing yet, so there may be more changes over the next while.