运行循环,创建绘图对象并将其显示在 flexdashboard 中

Running a loop creating plotly objects and displaying them in a flexdashboard

提问人:Andrew 提问时间:11/6/2023 最后编辑:Andrew 更新时间:11/7/2023 访问量:30

问:

我正在 flexdashboard 中运行一个循环,该循环生成绘图对象。但是,不会打印任何图表。代码中是否存在错误,或者 flexdashboard 和 plotly 之间是否存在兼容性问题?

---
title: "flexdashboard with Plotly Loop"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r}
    library(plotly)
    
    # Your vector of variables
    vec <- c("Sepal.Width", "Petal.Length", "Petal.Width")
    
    # Start a flexdashboard tabset
    cat("## Rows {.tabset}\n")
    
    # Loop through each variable
    for (yaxis in vec) {
      
      # Display the heading for the tab
      cat(paste0("### ", yaxis, "\n"))
      
      # Start the Plotly chart chunk
      cat("```{r}\n")   
      
      # Create the Plotly chart
      fig <- plot_ly(data = iris, 
                     x = ~Sepal.Length, 
                     y = ~.data[[yaxis]], 
                     type   = 'scatter', 
                     mode   = 'markers')
      
      # Print the chart
      print(fig)
      
      # End the chunk
      cat("```\n") 
    }

``
R 循环 Plotly FlexDashboard

评论


答:

0赞 stefan 11/7/2023 #1

调整我在这篇文章中的答案,该帖子处理标准 R-Markdown 文档的相同问题,您可以在循环中创建绘图图表,如下所示:

  1. 确保包含 JS 依赖项,为此,我添加了一个代码块,该代码块在我设置的循环之外创建一个空的绘图图。include=FALSE

  2. 无需使用 为代码块添加代码。实际上,这是行不通的,因为这只会在编织时将代码添加到您的 Markdown 中。但是,此代码块将不会被处理。cat()

  3. 相反,将你的绘图和结果包裹起来。htmltools::tagList()print

  4. 最后,添加 chunk 选项。results='asis'

完全可重现的代码:

---
title: "flexdashboard with Plotly Loop"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r include=FALSE}
library(plotly)

plot_ly()
```

```{r results='asis'}
# Your vector of variables
vec <- c("Sepal.Width", "Petal.Length")

# Start a flexdashboard tabset
cat("## Rows {.tabset}\n")

# Loop through each variable
for (yaxis in vec) {
  cat(paste0("### ", yaxis, "\n"))

  fig <- plot_ly(
    data = iris,
    x = ~Sepal.Length,
    y = ~ .data[[yaxis]],
    type = "scatter",
    mode = "markers"
  )

  print(
    htmltools::tagList(fig)
  )
}
```

enter image description here

评论

0赞 Andrew 11/8/2023
明。谢谢斯蒂芬。你有关于在flexdashboards中学习js使用的参考吗?