Plotly charts in a for loop

前端 未结 2 1058
我在风中等你
我在风中等你 2020-12-10 07:47

I am converting ggplot2 charts using plotly and putting them in a knitr html output. Here is a working copy of the report. http://rpubs.com/kausti/NSEFO-23-Mar-2016 The fir

相关标签:
2条回答
  • 2020-12-10 08:15

    It turns out the problem is solved here https://github.com/ropensci/plotly/issues/273

    knitr has known issues printing plotly charts in a loop. Quoting the final answer cpsievert from here

    ```{r}
    l <- htmltools::tagList()
    for (i in 1:3) {
      l[[i]] <- as.widget(plot_ly(x = rnorm(10)))
    }
    l
    ```
    

    This solved my problem. Though I ended up porting everything from ggplot2 to plotly R api before I found this solution.

    MLavoie, thanks for your help. I had generated a dummy dataset just to create a reproducible example. Though your solution probably solves the dummy example, it is not all that relevant to me in the current problem. I think the solution provided here should be generic.

    Thanks, Kaustubh

    0 讨论(0)
  • 2020-12-10 08:24

    I have a couple of alternatives for you. Let me know if it is helpful or not!

    Suggestion1 (base plotly using subplot):

    ```{r, echo=FALSE, message=FALSE, fig.width=8, fig.height=6}
    library(ggplot2)
    library(plotly)
    library(dplyr)
    s = NULL
    a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
    a$id2 <- as.integer(a$z)
    p <- plot_ly(a, x = x, y = y, group=z, xaxis = paste0("x", id2), mode = "markers")
    p <- subplot(p, nrows=3)
    p
    
    ```
    

    Suggestion2 (with ggplot2 but using facet):

    ```{r, echo=FALSE, message=FALSE, fig.width=8, fig.height=6}
    library(ggplot2)
    library(plotly)
    library(dplyr)
    s = NULL
    a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
    ggplotly(ggplot(a,aes(x = x, y = y)) + geom_point() + facet_grid(z~.))
    
    ```
    
    0 讨论(0)
提交回复
热议问题