Interactive `ggplotly` graph is not plotted from inside `for` loop in `Rmd` file in R

帅比萌擦擦* 提交于 2019-11-29 12:41:59

问题


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.


回答1:


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
  ```


来源:https://stackoverflow.com/questions/37013876/interactive-ggplotly-graph-is-not-plotted-from-inside-for-loop-in-rmd-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!