J. Doe
J. Doe

Reputation: 1750

Use purrr:map with ggplot

I don't have much experience using the purrr package. I have a dataframe named data which looks like this:

Country Year Incidence
USA     1995 20000
USA     2000 23000
UK      1995 16000
UK      2000 22000

It's confidential and I can't share it so this is just a small excrept. I need to make a plot where Year is on x-axis and incidence on y-axis, however, I need to have separate plots for each country. Faceting is unfortunately not an option, I need to save each plot as a separate file.

I know how I would split the dataframe, however, I don't know how to use ggplot inside of the map function. This is the code that I was trying with and is not working.

data %>%
  group_by(Country) %>%
  group_split() %>%
  map(ggplot, aes(x = Year, y = Incidence)+
        geom_line()+
        geom_point())

What would be the proper way to write this code?

Upvotes: 2

Views: 1262

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389315

You can use :

library(tidyverse)

list_plot <- data %>%
               group_split(Country) %>%
               map(~ggplot(., aes(x = Year, y = Incidence) ) +
                       geom_line()+ geom_point())

You get list of plots in list_plot one for every Country which can be accessed using list_plot[[1]], list_plot[[2]] etc.

Have you considered using facets for your plots?

Upvotes: 4

Related Questions