Using Flexdashboard, I want to put some text and a plot inside a loop - it should loop through variables, and I don't know how many there will be. But the plots appear side by side, not down the page, and the text is lost.
Example:
---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---
```{r}
library(ggplot2)
data(cars)
for(var in names(cars)) {
htmltools::tags$p(var)
print(ggplot(cars, aes_string(var)) +
geom_histogram())
}
```
Gives me:

If I don't loop, and instead just run the code for each variable:
---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---
```{r}
library(ggplot2)
data(cars)
var <- "speed"
htmltools::tags$p(var)
print(ggplot(cars, aes_string(var)) +
geom_histogram())
var <- "dist"
htmltools::tags$p(var)
print(ggplot(cars, aes_string(var)) +
geom_histogram())
```
I get what I expect:

Which is what I expect.
is there a way to get (something like) the second page, using the first code.
I'm having trouble getting the look to be exactly the same, but if you're ok with the name of the variable being indented along with the chart, this can work:
---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---
```{r}
library(tidyverse)
data(cars)
car_plots <- names(cars) %>%
set_names() %>%
map(~ ggplot(cars, aes(!! sym(.x))) + geom_histogram() + ggtitle(.x))
walk(names(cars), ~ print(car_plots[[.x]]))
```
In this case, the variable name is showing as a title to the chart, which is why it ends up being indented.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With