交互式`ggplotly`图不是从R中`Rmd`文件中的`for`循环内部绘制的

时间:2016-05-03 20:34:51

标签: r ggplot2 knitr plotly htmlwidgets

我尝试在R markdown(ggplotly)文件中的for循环内部绘制一系列交互式.Rmd图表。我的.Rmd文件的内容:

---
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))
}

```

我在Knit HTML中按RStudio按钮。不幸的是,.html文件中没有出现任何交互式图表。

问题:为什么不绘制图表?如何在for文件中结合Rmd循环创建交互式绘图?

P.S。如果我使用print(p)而不是print(ggplotly(p))ggplot2字符会显示在生成的.html文件中。

1 个答案:

答案 0 :(得分:13)

根据此github issue,您应该可以执行以下操作:

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