prdel99
prdel99

Reputation: 363

R print all ggplot graphs in markdown

I have dataframe like this:

library(ggplot2)
library(dplyr)


dt <-
  expand.grid(
    month = seq(1, 12),
    agent_id = seq(1, 1000)
  ) %>% 
  mutate(sales = row_number()) 

I would like to print graphs for all agent_id in markdown so I created this plot

src <- dt %>% filter(agent_id == 2)
title <- as.character(src$agent_id)

ggplot(src, aes(x = month, y = sales, group = 1)) +
  geom_line() +
  geom_point() +
  labs(title = title)

But how can I do it without calling

src <- dt %>% filter(agent_id == 2)

and

src <- dt %>% filter(agent_id == 3)

until 1000 or even higher id?

Upvotes: 0

Views: 114

Answers (1)

stefan
stefan

Reputation: 123768

You could split you dataset by agent_id, put your plotting code in a function then use iwalk to loop over the splitted list where iwalk allows to pass the name of the list element as a second argument to the plotting fcuntion to be used as title and the combo of iwalk + print avoids any console output:

---
title: "Untitled"
output: html_document
date: "2022-08-16"
---

```{r include=FALSE}
library(ggplot2)
library(dplyr)

dt <-
  expand.grid(
    month = seq(1, 12),
    agent_id = seq(1, 3)
  ) %>% 
  mutate(sales = row_number()) 
dt_split <- split(dt, dt$agent_id)
```

```{r}
purrr::iwalk(dt_split, function(x, y) {
  p <- ggplot(x, aes(x = month, y = sales, group = 1)) +
  geom_line() +
  geom_point() +
  labs(title = y)
  print(p)
})
```

enter image description here

Upvotes: 1

Related Questions