Rmarkdown(knitr chunk)文档中生成的多个(R)绘图图形 [英] multiple (R) plotly figures generated in a Rmarkdown (knitr chunk) document

查看:28
本文介绍了Rmarkdown(knitr chunk)文档中生成的多个(R)绘图图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用循环或 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.

这篇关于Rmarkdown(knitr chunk)文档中生成的多个(R)绘图图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆