How to Embed Plots into a Tab in Rmarkdown in a Procedural Fashion

How to embed plots into a tab in RMarkdown in a procedural fashion?

I played around a little and found a solution. You have to use print within the asis code chunk...

```{r}
library(ggplot2)
gg0 <- list()
gg0[[1]] <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
gg0[[2]] <- ggplot(mtcars, aes(mpg, disp)) + geom_point()
gg0[[3]] <- ggplot(mtcars, aes(mpg, drat)) + geom_point()

headings <- c('hp','disp','drat')
```

#### Heading {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(gg0)) {
cat("##### ",headings[i],"\n")
print(gg0[[i]])
cat('\n\n')
}
```

As an explanation, the cat command together with results='asis' produces the markdown code for a lower level headline and prints the ggplot graph afterwards. Since we used `{.tabset} in the parent headline, it creates the plots in separate tabs.

Dynamically control number of tabsets in R Markdown

If I add an extra newline at the end of each section, I get the desired results:

```{r, results='asis'}
headers <- list('graph 1', 'graph 2', 'graph 3')

for (h in headers){
cat("##", h, '<br>', '\n')
cat('This is text for', h, '<br>')
plot.new()
plot(diffinv(rnorm(100)), type = 'o', main = h)
cat('\n', '<br>', '\n\n')
}
```

Remember that Markdown often requires a full blank line between different elements.

Adjust .tabset panel html output length R

In RMarkdown we can control the size of plots using fig.dim fig. width or fig.height (see here).

In your case setting fig.height to 10 yields good results:

---
title: "test"
output: html_document
date: "2022-07-27"
---

```{r}
library(ggplot2)
library(patchwork)

gg0 <- list()

p1 <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, disp)) + geom_point()
p3 <- ggplot(mtcars, aes(mpg, drat)) + geom_point()

gg0[[1]] <- p1/p1/p1/p1
gg0[[2]] <- p1/p1/p1/p1/p1/p1
gg0[[3]] <- p1/p1/p1/p1/p1/p1/p1/p1/p1

headings <- c('hp','disp','drat')
```

#### Heading {.tabset}
```{r, results='asis', echo = FALSE, fig.height = 10}

for (i in 1:length(gg0)) {
cat("##### ",headings[i],"\n")
print(gg0[[i]])
cat('\n\n')
}
```


Related Topics



Leave a reply



Submit