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

标签 r knitr r-markdown plotly

我尝试使用循环或 lapply 在 Rmarkdown 文档中创建多个绘图图形。
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 块中时它会失败:
---
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)
```
我尝试用print(b) lapplyeval的组合替换parse,但只显示了最后一个数字。
我怀疑存在范围/环境问题,但找不到任何解决方案。

最佳答案

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

```{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 对象。

对于对技术背景感兴趣的人,您可能会看到 this blog post of mine 。简而言之,只打印顶级表达式。

关于r - 在 Rmarkdown(knitr chunk)文档中生成的多个(R)绘图图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35193612/

相关文章:

r - 如何使用 mouse 或 R 中的另一个包从多个变量中提取多个估算值到单个数据集中?

r - 包输入错误: Unicode char\u8 in RStudio

R光栅绘制图像,绘制一个圆圈并在圆圈外屏蔽像素

RStudio knitr markdown,德语变音符号导致代码块中的文本变为绿色

rmarkdown::render() 输出到标准输出

r - 使用 ggplot 绘制 y = mx + c

r - 以 PDF 和 PNG 格式保存图表,但在最终文档中使用 PDF 文件

knitr - 如何在 Rmarkdown 中制作图形标题?

r - 在 RMarkdown 中的数字周围添加空间

html - 在 R Markdown 中渲染原始 HTML