Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GGPlot within loop in Flexdashboard

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:

Plot of two histograms, side by side, no text.

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:

Two histograms, one of top of other, with text.

Which is what I expect.

is there a way to get (something like) the second page, using the first code.

like image 884
Jeremy Miles Avatar asked Jul 16 '26 20:07

Jeremy Miles


1 Answers

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.

enter image description here

like image 174
Phil Avatar answered Jul 19 '26 13:07

Phil



Donate For Us

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