3

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.

Jeremy Miles
  • 349
  • 1
  • 16

1 Answers1

2

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

Phil
  • 7,287
  • 3
  • 36
  • 66