0

I'm missing this is something very simple so hopefully should be an easy fix.

I'm producing a list of plotly heatmaps in one Rmarkdown code chunk and then want to embed them in the report in the next step, in a loop.

I'm trying:

---
title: "test"
output: html_document
---

```{r setup, include=FALSE,echo=FALSE}
knitr::opts_chunk$set(echo=FALSE,out.width='1000px',dpi=200,fig.keep="all")
options(width = 1000)
options(knitr.table.format = "html")

suppressPackageStartupMessages(library(dplyr))
suppressPackageStartupMessages(library(plotly))
suppressPackageStartupMessages(library(knitr))
```


```{r heatmaps, include=FALSE,echo=FALSE}
set.seed(1)
heatmaps.list <- vector(mode="list",3)
for (i in 1:3) heatmaps.list[[i]] <- plot_ly(z = matrix(rnorm(10000),100,100), type = "heatmap")
```

```{r plots, include=FALSE,echo=FALSE}
for (i in 1:3){
  heatmaps.list[[i]]
  cat("\n")
}
```

Unfortunately this is not embedding the heatmaps although they are produced in the heatmaps Rmarkdown code chunk.

If I try this with base plot is seems to work:

```{r heatmaps, include=FALSE,echo=FALSE}
set.seed(1)
hist.list <- vector(mode="list",3)
for (i in 1:3){
  hist.list[[i]] <- hist(rnorm(10000),plot=F)
}
```

```{r plot, warning=FALSE,message=FALSE,echo=FALSE}
for (i in 1:3){
  plot(hist.list[[i]])
  cat("\n")  
}
```
dan
  • 6,048
  • 10
  • 57
  • 125

1 Answers1

1

I get the same error even with a simpler setup

---
output: html_document
---

```{r setup}
suppressPackageStartupMessages(library(plotly))

# this works
plot_ly(z = matrix(rnorm(100), 10, 10), type = "heatmap")

# this does not
set.seed(1)
for (i in 1:3)
  plot_ly(z = matrix(rnorm(100), 10, 10), type = "heatmap")
```

The fact that you want to save the plots ab objets is not the problem, it's the loop. The answer from here is to use

htmltools::tagList(as_widget(plot1), as_widget(plot2))

instead. For my minimal example, this would be.

---
output: html_document
---

```{r setup}
suppressPackageStartupMessages(library(plotly))

# now it works
set.seed(1)
l <- htmltools::tagList()
for (i in 1:3) 
  l[[i]] = as_widget(plot_ly(z = matrix(rnorm(100), 10, 10), type = "heatmap") )
l
```

Unfortunately, I don't have the rep to mark duplicates.

Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43