【问题标题】:Using `ggplotly` and `DT` from a `for` loop in Rmarkdown在 Rmarkdown 的“for”循环中使用“ggplotly”和“DT”
【发布时间】:2020-06-26 08:45:26
【问题描述】:

是否可以在 for 循环或函数内部在 RMarkdown 中使用 ggplotly()datatable()?示例:

---
title: "Using `ggplotly` and `DT` from a `for` loop in Rmarkdown"
output: html_document
---

```{r setup, include=FALSE}
library(ggplot2); library(DT)
```

## Without `for` loop - works

```{r}
datatable(cars)

g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[1] ))
ggplotly(g) 
```

## From inside the `for` loop  - does not work (nothing is printed)

```{r}
for( col in 1:ncol(cars)) {

  datatable(cars)          # <-- does not work 
  print( datatable(cars) ) # <-- does not work either

  g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[col] ) )

  ggplotly (g)            # <-- does not work 
  print ( ggplotly (g) )  # <-- does not work either
}
```

我想知道这是否是因为 interactive 输出根本不可能是 print-ed - 设计使然。
打印非交互式输出时不存在此类问题。

PS 这与: Automating the generation of preformated text in Rmarkdown using R
Looping headers/sections in rmarkdown?

【问题讨论】:

  • 感谢您的链接 - 我看了看。它确实提供了一个解决方案,但前提是您只想循环 ggplotly(为此,您需要停止使用 ggplot2 并直接使用 plotly)。但是,我正在尝试将文本、图形、表格组合在一起——所有这些都是在打印每个部分标题后自动生成的。
  • 你仍然可以使用 ggplotly。见stackoverflow.com/questions/61906480/…。也可以组合不同的htmlwidgets
  • 找到此相关链接(for 内部的ggplotly .Rmd 文件中的循环不起作用)。 github.com/ropensci/plotly/issues/570 - 好像还没有解决:(

标签: r r-markdown dt ggplotly r-glue


【解决方案1】:

这是我在评论中添加的post 的解决方案,适用于您的情况:

---
title: "Using `ggplotly` and `DT` from a `for` loop in Rmarkdown"
output: html_document
---

```{r setup, include=FALSE}
library(plotly); library(DT)
```

```{r, include=FALSE}
# Init Step to make sure that the dependencies are loaded
htmltools::tagList(datatable(cars))
htmltools::tagList(ggplotly(ggplot()))
```

```{r, results='asis'}
for( col in 1:ncol(cars)) {
  
  print(htmltools::tagList(datatable(cars)))
  
  g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[col] ) )

  print(htmltools::tagList(ggplotly(g)))

}
```

【讨论】:

  • 这很棒。但是我不明白为什么需要启动汽车。我在我的电脑上试过了,没有初始化步骤它就失败了。我问的原因是因为我有一个使用 for 循环的复杂表列表,我似乎无法使用 for 循环启动!
  • 从头开始评论:要让列表工作只需简单地用 lappy 启动,就像这样,l = list ( c=cars, c2=iris ) htmltools::tagList( lapply(l, datatable) )
  • 嗨@Ahdee。我们不需要初始化汽车。 init 步骤确保 javascript 依赖项,即 plotly.js 和 DataTables.js,包含在 html 文档中。
【解决方案2】:

这似乎是 RMarkdown 的一个长期存在的问题。然而,这是解决方法,发现 here:

lotlist = list()

for (VAR in factor_vars) {
    p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()
    plotlist[[VAR]] = ggplotly(p)
}
htmltools::tagList(setNames(plotlist, NULL))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 2020-11-05
    • 1970-01-01
    • 2018-06-15
    • 2019-01-12
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多