Search code examples
rggplot2geom-area

Insert legend into geom_area plot


Is it possible to insert the legend of a ggplot::geom_area() into the respective areas?

I.e., I would like to change

enter image description here

to:

enter image description here

(source for the plot: https://www.geeksforgeeks.org/stacked-area-chart-with-r/)


Solution

  • You can use geom_text with position_fill. You will also need to filter to include only a single year of your choosing:

    ggplot(data, aes(x = year, y = percentage, fill = group)) +
      geom_area(alpha = 0.8, size = 0.5, colour = "white") +
      geom_text(aes(label = group), position = position_fill(vjust = 0.5),
                data = . %>% filter(year == 2018)) +
      scale_fill_viridis(discrete = TRUE) + 
      theme_ipsum() +
      ggtitle("Percentage Stacked-Area Plot")
    

    enter image description here


    Data used

    We would normally ask that questions contain the necessary data and code directly rather than pointing to external links. External links may change, and there have been instances of spammy or malicious links. I have harvested the relevant code from the link provided for others to reproduce the plot here:

    library(tidyverse)
    library(viridis)
    library(hrbrthemes)
    
    set.seed(1)
    
    group <- rep(c("NORTH", "SOUTH", "EAST", "WEST"), times = 4)  
    year  <- as.numeric(rep(seq(2017, 2020), each = 4)) 
    price <- runif(16, 50, 100)
    data  <- data.frame(year, price, group)
    
    data <- data  %>%
      group_by(year, group) %>%
      summarise(n = sum(price)) %>%
      mutate(percentage = n / sum(n))