在R的Rmd文件中,使用for循环创建`ggplotly`交互式图表无法正常绘制

18

我尝试在R markdown(.Rmd)文件的for循环中绘制一系列交互式ggplotly图形。我的.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))
}

```

我在 RStudio 中点击了 Knit HTML 按钮,但遗憾的是,交互式图形并没有出现在生成的 .html 文件中。

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

p.s. 如果我使用 print(p) 而不是 print(ggplotly(p)),那么 ggplot2 绘制的图形会出现在生成的 .html 文件中。

1个回答

19

根据这个GitHub问题,您应该能够像这样做:

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

不错的解决方案。不幸的是,在我的当前自动化分析中,我无法使用它,因为在每次for循环迭代中,图表都会跟随表格和一些统计测试结果。将所有图表打印在一个地方会令人困惑。我注意到,pander()的结果也无法从for循环内部打印。这是knitr的某个错误吗? - GegznaV
看起来你也在 Github 存储库上提出了你的关注。最好与 timelyportfolio 合作解决这个问题。 - royr2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接