18

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
GegznaV
  • 4,938
  • 4
  • 23
  • 43

1 Answers1

19

Based on this github issue, you should be able to do something like this:

  ---
  title: "Untitled"
  output: html_document
  ---

  ```{r, message = F}
  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])) 

  plt <- htmltools::tagList()
  i <- 1
  for (VAR in factor_vars) {

      # Contents of "VAR" changes inside the loop
      p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + 
        geom_point() + 
        ggtitle(paste("Factor variable:", VAR))


      # Print an interactive plot
      # Add to list
      plt[[i]] <- as.widget(ggplotly(p))
      i <- i + 1
  }

  ```

  ```{r, echo = F}
  plt
  ```
royr2
  • 2,239
  • 15
  • 20
  • Nice workarround. Unfortunately, I'm not able to use it in my current automated analysis where in each iteration of `for` loop plots are followed by tables, results some statistical tests. Printing all plots in one place would be confusing. I noticed, that result of `pander()` also does not print from inside `for` loop. Is it some bug in `knitr`? – GegznaV May 04 '16 at 21:06
  • Looks like you raised your concern on the github repo as well. Probably best if you work with timelyportfolio on this. – royr2 May 06 '16 at 06:31