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
# Convert 4 variables to factor variables:
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.