Programmatically create tab and plot in markdown

微笑、不失礼 提交于 2020-12-23 11:07:49

问题


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

回答1:


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

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



来源:https://stackoverflow.com/questions/63397427/programmatically-create-tab-and-plot-in-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!