Plotly charts in a for loop

百般思念 提交于 2019-11-29 08:42:10

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

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~.))

```
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!