I tried to plot series of interactive ggplotly graphs from inside for loop in R markdown (.Rmd) file. Contents of my .Rmd file:
``````
title: "Untitled"
output: html_document
```{r}
library(ggplot2) # for plots
library(plotly) # for interactive plots
factor_vars <- c("vs", "am", "gear", "carb")
mtcars[factor_vars] <- data.frame(Map(as.factor, mtcars[factor_vars]))
for (VAR in factor_vars) {
cat(paste("Factor variable:", VAR))
# Contents of "VAR" changes inside the loop
p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()
# Print an interactive plot
print(ggplotly(p))
}
```
``````
I push Knit HTML button in RStudio. Unfortunately, none of interactive plots appear in the .html file.
Question: why the graphs aren't plotted? And how can I create interactive plot in combination with for loop in Rmd file?
p.s. If I use print(p) instead of print(ggplotly(p)), ggplot2 plots appear in resulting .html file.
See this comment.
I'll open an issue in our documentation repo to make sure we have better docs of this...
Is this problem solved? I seem to have the same issue.
The current workaround is (based on the example code in the original issue):
plotlist = list()
for (VAR in factor_vars) {
p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()
plotlist[[VAR]] = ggplotly(p)
}
htmltools::tagList(setNames(plotlist, NULL))
Although I sometimes get memory access errors from pandoc when I try to do this.
Most helpful comment
Is this problem solved? I seem to have the same issue.