Programmatically create tab and plot in markdown
Asked Answered
G

1

6

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))
        })
```
Gravitation answered 13/8, 2020 at 14:34 Comment(2)
Is that highcharter::hchart? Please be clear with non-base packages (dplyr too, safe to infer based on purrr?).Whiffen
@Whiffen yes. sorry for thatGravitation
G
8

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}   \n')
invisible(
  iris %>% 
      dplyr::group_split(Species) %>% 
      purrr::imap(.,~{
        # create tabset for each group 
        cat('### Tab',.y,'   \n')
        cat('\n')
        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

Gaylene answered 16/8, 2020 at 12:41 Comment(2)
thx a lot! highchart(height = 1) and tagList were good advice!Gravitation
Works for .Rmd - as in the question - however the tabs do not appear in quartoInduration

© 2022 - 2024 — McMap. All rights reserved.