J. Doe
J. Doe

Reputation: 1740

ggplot - add title based on the variable in the dataframe used for plotting

This is a follow-up to my previous question where I asked how to use ggplot inside of purr::map.

I have a dataframe that looks like this:

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

I am using this code to make a year/incidence plot split by country (each country has a separate plot, not one single, but faceted plot for all countries).

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

Now I would like to put the name of the country in the title of each of the graphs. I tried the following:

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

But it's not working (it's telling me the object 'Country' is not found). How can I achieve this?

Upvotes: 1

Views: 1083

Answers (1)

camnesia
camnesia

Reputation: 2323

Using .$Country instead of Country should fix it

data = data.frame(Country = c('USA','USA','UK','UK'), 
                  Year = c(1995,2000,1995,2000), 
                  Incidence = c(20000,23000,16000,22000))

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

Upvotes: 3

Related Questions