1

I was trying to create an rmarkdown file which dynamically loads a list of plotly objects with predefined comments. The minimal example code is listed below:

Currently, this chunk is failing at multiple levels: 1) plots do not show up properly - I tried to put htmltools::tagList(ls_ply) at very end, it throws out an error. 2) I expected to make the comment as header, however, I know if I applied results='asis' in chunk beginning, it would disable the plot.

```{r, echo=FALSE, message=FALSE}
library(plotly)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
art1 <- list(viz = p1, comment = 'article1')
p2 <- qplot(carat, price, data=dsamp, colour=carat)
art2 <- list(viz = p2, comment = 'article2')
ls_ply <- lapply(list(art1,art2),function(art){
  cat('## ',art$comment,'\n')
  art$viz
})
```
Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
Xiushi Le
  • 245
  • 3
  • 16

1 Answers1

0

For ggplot plots:

```{r, echo=FALSE, message=FALSE, results='asis'}
library(ggplot2)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
art1 <- list(viz = p1, comment = 'article1')
p2 <- qplot(carat, price, data=dsamp, colour=carat)
art2 <- list(viz = p2, comment = 'article2')

art <- list(art1, art2)
for (i in seq_len(length(art))) {
  cat(sprintf("\n\n## %s\n", art[[i]]$comment))
  print(art[[i]]$viz)
}
```

However, this can't be extended to plotly objects. This is a known problem with only solution is to regroup all plots and plot them at once, which is not what you want here.

Maybe using knit_expand could help, but knit_child doesn't work for me directly.

F. Privé
  • 11,423
  • 2
  • 27
  • 78
  • Thanks. I found an alternative solution working for me. [link](http://stackoverflow.com/questions/37008600/dynamically-loop-through-htmlwidgets-and-add-knitr-formatting-for-rmarkdown) – Xiushi Le Sep 12 '16 at 14:43