Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

r - Programmatically create tab and plot in markdown

I'm trying to create a dynamic number of tabs in my rmd with some content inside.
This one doesn't help.
Something like this:

---
title: "1"
output: html_document
---

```{r }
library(highcharter)
library(tidyverse)
iris %>% 
      dplyr::group_split(Species) %>% 
      purrr::map(.,~{
        # create tabset for each group 
        ..1 %>% 
          hchart("scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
        })
```
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can set results = 'asis' knitr option to generate the tabs in the map function using cat.

Getting Highcharter to work with asis was trickier :

  • Highchart needs to be called once before the asis chunck, probably to initialize properly, hence the first empty chart.
  • to print the chart in the asis chunck, the HTML output is sent in character format to cat

Try this:

---
title: "Test tabs"
output: html_document
---

`r knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = F)`

```{r}
library(highcharter)
library(tidyverse)
# This empty chart is necessary to initialize Highcharter in the tabs
highchart(height = 1)
```


```{r, results = 'asis'}
cat('## Tabs panel {.tabset}   
')
invisible(
  iris %>% 
      dplyr::group_split(Species) %>% 
      purrr::imap(.,~{
        # create tabset for each group 
        cat('### Tab',.y,'   
')
        cat('
')
        p <- hchart(.x,"scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
        cat(as.character(htmltools::tagList(p)))
      })
)
```

enter image description here

Note that while this solution works well, it goes beyond the original use for asis


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...