Rmarkdown(knitr chunk)文档中生成的多个(R)绘图图形多个、图形、文档、Rmarkdown

由网友(毕业时可以抱你么)分享简介:我尝试使用循环或 lapply 在 Rmarkdown 文档中创建多个绘图图形.I try to create multiple plotly figures in a Rmarkdown document using loop or lapply.R 脚本:require(plotly)data(iris)...

我尝试使用循环或 lapply 在 Rmarkdown 文档中创建多个绘图图形.

I try to create multiple plotly figures in a Rmarkdown document using loop or lapply.

R 脚本:

require(plotly)
data(iris)
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")),
            function(x) {
              plot_ly(iris, 
                      x = iris[["Sepal.Length"]],
                      y = iris[[x]], 
                      mode = "markers")
            })
print(b)

效果很好,但是当包含在 knitr 块中时会失败:

works well, but it fails when included in a knitr chunk:

---
output: html_document
---

```{r,results='asis'}
require(plotly)
data(iris)
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")),
            function(x) {
              plot_ly(iris, 
                      x = iris[["Sepal.Length"]],
                      y = iris[[x]], 
                      mode = "markers")
            })
print(b)
```

我尝试用 lapply evalparse 的组合替换 print(b) 但只有最后一个图已显示.

I tried replacing print(b) with a combination of lapply eval and parse but only the last figure was displayed.

我怀疑存在范围/环境问题,但我找不到任何解决方案.

I suspect a scoping/environment issue but I cannot find any solution.

推荐答案

print(b) 放在 htmltools::tagList() 中,而不是 print(b),例如

```{r}
library(plotly)

b <- lapply(
  setdiff(names(iris),
          c("Sepal.Length","Species")),
  function(x) {
    plot_ly(iris, 
            x = iris[["Sepal.Length"]],
            y = iris[[x]], 
            mode = "markers")
  }
)

htmltools::tagList(b)
```

注意:在 Plotly v4 之前,需要使用 Plotly 的 as.widget() 函数将 Plotly 对象转换为 htmlwidgets.从 Plotly v4 开始,它们默认是 htmlwiget 对象.

Note: Before Plotly v4 it was necessary to convert the Plotly objects to htmlwidgets using Plotly's as.widget() function. As of Plotly v4 they are htmlwiget objects by default.

对技术背景感兴趣的朋友可以看看我的这篇博文.简而言之,只有 顶级 表达式会被打印出来.

For people who are interested in the technical background, you may see this blog post of mine. In short, only top-level expressions get printed.