Home > Back-end >  How can I add mean of stat_summary in a legend?
How can I add mean of stat_summary in a legend?

Time:11-22

I have created an average with the stat_summary() function, but I can't add it to the legend. I wonder, is it possible to do this?

Here is my code:

gap %>%
  filter(country %in% c("Angola","Botswana","Lesotho","Malawi","Mozambique",
                        "Namibia","Swaziland","South Africa","Zambia","Zimbawe")) %>%
  ggplot(aes(x=year,y=life_expectancy, col=country))   
  geom_line(size=1.2, alpha=0.7) 
  stat_summary(fun = mean,geom = "line", size= 1.5,col="black") 
  theme_light() 
  labs(title="Evolució de l'expectativa de vida en l’Àfrica Austral",
       x= "1960-2016",
       y="Expectativa de vida",
       col= "Llegenda",
       tag = "Fig. 3")

Help would be very appreciated, thanks!

I have tried tutorials but the only thing I have achieved is to remove the legend of all the countries and that only the legend of the average appears and that is not what I need.

CodePudding user response:

One option would be to map on aesthetics, i.e. use the color aes in stat_summary and set your desired colors via scale_color_manual.

Using the gapminder::gapminder dataset as example data:

library(ggplot2)
library(dplyr)
library(gapminder)

# example data
gap <- gapminder |>
  rename(life_expectancy = lifeExp)

cntrys <- c(
  "Angola", "Botswana", "Lesotho", "Malawi", "Mozambique",
  "Namibia", "Swaziland", "South Africa", "Zambia", "Zimbawe"
)
pal_color <- c(scales::hue_pal()(length(cntrys)), "black")
names(pal_color) <- c(cntrys, "Mean life expectancy")

gap %>%
  filter(country %in% cntrys) %>%
  ggplot(aes(x = year, y = life_expectancy, col = country))  
  geom_line(size = 1.2, alpha = 0.7)  
  stat_summary(aes(color = "Mean life expectancy"), fun = mean, geom = "line", size = 1.5)  
  scale_color_manual(values = pal_color, breaks = names(pal_color))  
  theme_light()  
  labs(
    title = "Evolució de l'expectativa de vida en l’Àfrica Austral",
    x = "1960-2016",
    y = "Expectativa de vida",
    col = "Llegenda",
    tag = "Fig. 3"
  )
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.

  • Related