我尝试使用循环或 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)
lapply
和eval
的组合替换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/