If you run the following to create an HTML document, you see that it creates a separate bar chart for the three iris species.
In order to print this list of plotly charts in an HTML document that were created in a loop, you have to store the charts in a list and run that htmltools line after the loop to get them to display properly; you can't just print(charts).
However, I want it to simply print the species name before printing the chart. Then the same for the next and so on. This is so you can know which group each chart represents.
I know that you could just add a title to each chart in the loop with a plot_ly argument. However, I'm just using these bar charts as a simple example; my actual report uses another similar package that doesn't have an option for including titles directly in the chart but otherwise works the same way. This is why I'm trying to figure out how to simply get it to print "setosa", then display the barchart, "versicolor", then display the bar chart, etc. I'm not sure how to do this using htmltools.
---
title: "Test"
output: html_document
---
```{r charts, echo=FALSE, message=FALSE}
library("plotly")
charts<-list()
for(i in 1:length(unique(iris$Species))){
iris2<-iris[iris$Species==unique(iris$Species)[i],]
charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar')
}
htmltools::tagList(charts)
```
Here's an example of what I'm trying to do (just displays the first group in this image):
You can make another list and append text to the plots. Basic idea is the following chunk of code:
list(tags$h1(unique(iris$Species)[i]),
tags$figure(charts[[i]]))
You can check ?taglist
and arguments of tag$...
to have a better understanding where this idea is coming from. See the answer below:
---
title: "Test"
output: html_document
---
```{r charts, echo=FALSE, message=FALSE}
library("plotly")
library("htmltools")
charts <- list()
for(i in 1:length(unique(iris$Species))){
iris2 <- iris[iris$Species==unique(iris$Species)[i],]
charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar')
}
tgls <- list()
for(i in 1:length(unique(iris$Species))){
tgls[[i]] <- list(tags$h1(unique(iris$Species)[i]),
tags$figure(charts[[i]]))
}
tagList(tgls)
```
I am not sure why you cannot use %>% layout(title="plot title")
. You may want to share the actual package that you are using for potting to get a more straightforward answer. For the sake of completion, I post a solution with plotly
arguments as well.
---
title: "Test"
output: html_document
---
```{r charts, echo=FALSE, message=FALSE}
library("plotly")
charts<-list()
for(i in 1:length(unique(iris$Species))){
iris2<-iris[iris$Species==unique(iris$Species)[i],]
charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar') %>%
layout(title=as.character(unique(iris$Species)[i]))
}
htmltools::tagList(charts)
```