Search code examples
rggplot2legendstacked-area-chart

Plot labels at ends of lines in stacked area chart


I have the following code

library(ggplot2)
library(dplyr)

# create data
time <- as.numeric(rep(seq(1,7),each=7))  # x Axis
value <- runif(49, 10, 100)               # y Axis
group <- rep(LETTERS[1:7],times=7)        # group, one shape per group
data <- data.frame(time, value, group)

# stacked area chart
ggplot(data, aes(x=time, y=value, fill=group)) + 
  geom_area()+
  geom_text(data = data %>% filter(time == last(time)), aes(label = group, 
                                                               x = time + 0.5, 
                                                               y = value, 
                                                               color = group)) + 
  guides(color = FALSE) + theme_bw() + 
  scale_x_continuous(breaks = scales::pretty_breaks(10))

Where i getenter image description here

But i am aiming for link

Is there any solution for stacked area plot?


Solution

  • The question code is plotting the text labels in the value's of the last time, when in fact the areas are cumulative. And in reverse order.

    Also, the following graph plots data created with the same code but with

    set.seed(1234)
    

    Then the data creation code is the same as in the question.

    # stacked area chart
    ggplot(data, aes(x=time, y=value, fill=group)) + 
      geom_area()+
      geom_text(data = data %>% 
                  filter(time == last(time)) %>%
                  mutate(value = cumsum(rev(value))), 
                aes(label = rev(group), 
                    x = time + 0.5, 
                    y = value, 
                    color = rev(group))) + 
      guides(color = FALSE) + theme_bw() + 
      scale_x_continuous(breaks = scales::pretty_breaks(10))
    

    enter image description here

    Edit.

    Following the discussion in the comments to this answer, I have decided to post code based on the comment by user Jake Kaupp.

    ggplot(data, aes(x = time, y = value, fill = group)) + 
      geom_area()+
      geom_text(data = data %>% filter(time == last(time)),
                aes(x = time + 0.5, y = value, 
                    label = rev(group), color = rev(group)),
                position = position_stack(vjust = 0.5)) + 
      guides(color = FALSE) + 
      theme_bw() + 
      scale_x_continuous(breaks = scales::pretty_breaks(10))