Plotly图不会在RMarkdown文档的for循环内呈现

Ben*_*Ben 8 r knitr r-markdown plotly

我正在尝试动态构建一个需要运行循环的报表,并且每次迭代都会打印一些消息,表格和一个图表.除了情节,我可以把一切都搞定.

example.rmd

```{r echo=FALSE, results='asis', fig.keep='all', message = FALSE, warning = FALSE}
library(knitr)
library(plotly)

for(i in 1:4){
  foo <- iris[sample(nrow(iris), 20), ]

  cat("\n")
  cat("# Iteration", i, "\n")

  # Print the first few lines
  print(kable(head(foo)))
  cat("\n")

  # Plot Sepal.Width vs Petal.Length using ggplotly()
  plt <- ggplot(foo, aes(x = Sepal.Width, y = Petal.Length))+geom_point()

  # plot(plt)  # <- this works
  # plot(ggplotly(plt))  # <- this doesn't work
  # ggplotly(plt)  # <- this doesn't work

  cat("\n")
}
```
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如何在报告中绘制情节图?

Ben*_*Ben 8

github关于基本相同问题的这篇文章之后,我能够把这个非常hacky的解决方案放在一起.很想找到更好的方法.

```{r echo=FALSE, results='asis', fig.keep='all', message = FALSE, warning = FALSE}
library(knitr)
library(plotly)

# Build list of outputs
output <- list()
for(i in 1:4){
  foo <- iris[sample(nrow(iris), 20), ]

  # Header for iteration
  txt <- paste0("#Iteration ", i)
  output[[length(output) + 1L]] <- txt

  # Table of the first few lines
  tbl <- kable(head(foo))
  output[[length(output) + 1L]] <- tbl

  # Plot
  plt <- ggplotly(ggplot(foo, aes(x = Sepal.Width, y = Petal.Length))+geom_point())
  output[[length(output) + 1L]] <- plt
}

# Render the outputs
for(j in 1:length(output)){
  x <- output[[j]]

  if(inherits(x, "character")){
    cat("\n")
    cat(x)
  } else if(inherits(x, "knitr_kable")){
    cat("\n")
    print(x)
  }
  else {
    # print the html piece of the htmlwidgets
    cat("\n")
    cat(htmltools::renderTags(as.widget(x))$html)
  }
}
```

```{r echo=FALSE, messages=FALSE, warning=FALSE}
# Attach the Dependencies since they do not get included with renderTags(...)$html
deps <- lapply(
  Filter(f = function(x){inherits(x,"htmlwidget")}, x = output),
  function(hw){
    htmltools::renderTags(hw)$dependencies
  }
)
htmltools::attachDependencies(x = htmltools::tagList(), value = unlist(deps,recursive=FALSE))
```
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 您分享给Github问题的链接最有帮助.在Yihui在[this](https://github.com/ramnathv/htmlwidgets/pull/110)PR中为`htmlwidgets`解释之前,我不能轻易推理出解决方案. (2认同)