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

2023-09-06 07:19:49 作者:离人醉℡

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

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

```

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

I push Knit HTML button in RStudio. Unfortunately, none of interactive plots appear in the .html file.

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

Question: why the graphs aren't plotted? And how can I create interactive plot in combination with for loop in Rmd file?

附言如果我使用 print(p) 而不是 print(ggplotly(p))ggplot2 图会出现在生成的 .html文件.

p.s. If I use print(p) instead of print(ggplotly(p)), ggplot2 plots appear in resulting .html file.

推荐答案

基于这个github问题,你应该能够做这样的事情:

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