-
DescriptionIs it possible to programmatically create multiple sections each containing multiple plots, where each plot is from an R computation and can have adjustable figure dimensions? Basically I would like to create two plots in each section, one large and one small. I have tried wrapping these plots in figure divs with different See below I have programmatically generated markdown sections, 1 for each category of a variable in ---
title: "Dynamically creating sections with multiple plots"
format:
html:
toc: true
keep-md: true
engine: knitr
editor_options:
chunk_output_type: console
---
```{r}
library(dplyr)
library(ggplot2)
library(purrr)
generate_md_sections <- function(section) {
# plot 1 (large)
cat('\n\n##', section, '\n\n')
cat("\n::: {#fig-", section, "-large height=600}\n\n", sep="")
p <- mtcars |>
ggplot(aes(x = disp, y = hp)) +
geom_point() +
labs(title = section)
plot(p)
cat('\n\nlarge. End of caption\n')
cat('\n\n:::\n\n')
# plot 2 (small)
cat("\n::: {#fig-", section, "-small height=200}\n\n", sep="")
plot(p)
cat('\n\nsmall\n')
cat('\n\n:::\n\n')
}
sections <- mtcars$cyl |> unique() |> sort()
```
```{r}
#| results: "asis"
walk(sections, generate_md_sections)
```
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
That's |
Beta Was this translation helpful? Give feedback.
-
Thank you @mcanouil This is a solution to above using ---
title: "Dynamically creating sections with multiple plots"
format:
html:
toc: true
keep-md: true
engine: knitr
editor_options:
chunk_output_type: console
---
```{r}
library(dplyr)
library(ggplot2)
library(purrr)
sections <- mtcars$cyl |> unique() |> sort()
```
```{r, echo=FALSE, results='asis'}
res <- purrr::map(sections, function(x) {
knitr::knit_child(text = c(
'## Plot "`r x`"',
'',
'```{r}',
'#| fig-height: 10',
'p <- mtcars |>
ggplot(aes(x = disp, y = hp)) +
geom_point() +
labs(title = x)
plot(p)',
'```',
'',
'```{r}',
'#| fig-height: 2',
'p <- mtcars |>
ggplot(aes(x = disp, y = hp)) +
geom_point() +
labs(title = x)
plot(p)',
'```',
''
), envir = environment(), quiet = TRUE)
})
cat(unlist(res), sep = '\n')
```
|
Beta Was this translation helpful? Give feedback.
Thank you @mcanouil
This is a solution to above using
knitr::knit_child()