plotly对象在R Markdown中不可见

w6lpcovy  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(142)

我是R-Markdown的新手,我在HTML报告中渲染plotly对象时遇到问题。问题是for loop。当我在for loop中创建图形时,它们在最终报告中不可见。我找到了单循环的解决方案:LINK双循环中的情况如何?我不能将解决方案从单循环转换为例如2个嵌套循环。总结:
1.FOR LOOP

  • 打印不可见:
plots <- list()
for(i in 1:3) {
   l[[i]] <- plot_ly(x = rnorm(10))
}
l
  • 图可见:
l <- htmltools::tagList()
for (i in 1:3) {
  l[[i]] <- plot_ly(x = rnorm(10))
}
l

1.双人FOR LOOP

  • 打印不可见:
for(j in 1:3){
# some text, tables depends of j
# transform dataset based on `j`
  l <- htmltools::tagList()
  for (i in 1:3) {
     l[[i]] <- plot_ly(x = rnorm(10))
  }
  l # <-plot on the end of each j loop, not on the end of whole loop like was in single for loop
}
  • 图可见:??

有什么办法解决这个问题吗?我将非常感谢任何帮助!

EDIT:代码示例

#' ---
#' title: "Sample Document"
#' output:
#'   html_document:
#'   toc: true
#' theme: united
#' ---

#' R Markdown report of graphs generated with a double (nested) for loop

df <- data.frame(
  j = numeric(),
  desc = character()
)

for(j in c(1:3)){
  cat(paste0("# below we present visualizations for iteration no.: ", j, "\n"))
  
  #' Random table
  #+ echo=FALSE, results = 'asis'
  df <- rbind(df, data.frame(j = j, desc = paste0("iteration no.: ", j)))
  print(knitr::kable(df, row.names = F))
  
  l <- htmltools::tagList()
  for(i in (1:3)){
    l[[i]] <- plot_ly(x = j*rnorm(i*10))
    print(l[[i]])
  }
}
sy5wg1nm

sy5wg1nm1#

基本上,你可以用同样的方法来实现这一点,把外部循环 Package 在第二个tagList中:

---
title: "Untitled"
output: html_document
date: "2023-04-12"
---

```{r echo=FALSE, message=FALSE}
library(plotly)

Using lapply

htmltools::tagList(
  lapply(1:2, function(j) {
    l <- htmltools::tagList()
    for (i in 1:2) {
      l[[i]] <- plot_ly(x = rnorm(10)) |>
        layout(title = paste(j, i, sep = "."))
    }
    l
  })
)

Using a for loop

ll <- htmltools::tagList()

for (j in 1:2) {
  l <- htmltools::tagList()
  for (i in 1:2) {
    l[[i]] <- plot_ly(x = rnorm(10)) |>
      layout(title = paste(j, i, sep = "."))
  }
  ll[[j]] <- l
}
ll

![](https://i.stack.imgur.com/rRIAR.png)

**编辑**将我在这篇文章中的答案调整到您的案例中,您可以像这样实现您想要的结果。重要的一步是确保包含JS依赖项。然后您可以使用`print`打印在内部循环中创建的图。

title: "Untitled"
output:
html_document:
toc: true
theme: united
date: "2023-04-12"

knitr::opts_chunk$set(message = FALSE)
library(plotly)
df <- data.frame(
  j = numeric(),
  desc = character()
)
# Init Step to make sure that the dependencies are loaded
htmltools::tagList(plot_ly(x = rnorm(10), type = "histogram"))
for (j in 1:2) {
  cat(paste0("# below we present visualizations for iteration no.: ", j, "\n"))

  df <- rbind(df, data.frame(j = j, desc = paste0("iteration no.: ", j)))
  print(knitr::kable(df, row.names = F))

  l <- htmltools::tagList()
  for (i in 1:2) {
    l[[i]] <- plot_ly(x = j * rnorm(i * 10))
  }
  print(l)
}

![](https://i.stack.imgur.com/G9Yiu.png)

相关问题