Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I try to create multiple plotly figures in a Rmarkdown document using loop or lapply.

The R script:

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)
```

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 cannot find any solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
588 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)
```

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...