在rmarkdown(编织程序块)文档中生成的多个(R)可绘制图形 [英] multiple (R) plotly figures generated in a rmarkdown (knitr chunk) document

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

问题描述

我尝试使用loop或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)

效果很好,但是如果包含在编织块中则失败:

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 don't find any solution.

推荐答案

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

Instead of print(b), put b in htmltools::tagList(), e.g.

```{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对象转换为htmlwidget.从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(编织程序块)文档中生成的多个(R)可绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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