Search code examples
rggplot2geom-area

Add a line from a different dataframe to a stacked area chart in R


I have a data frame that was the result of pivot_longer, from which I've made a stacked area chart. I now want to overlay a geom_line on top of this chart. Right now, the data for geom_line comes from a different dataset, which is unpivotted (ie the value is in it's own column). I've tried the following:

df_long <- df %>% pivot_longer(cols = c('A', 'B', 'C', 'D'), names_to='metric', values_to='value')

ggplot(df_long, aes(x=time, y=value, fill=metric)) + 
  geom_area(alpha=0.6 , linewidth=0.5, colour="white") +
  scale_fill_viridis(discrete = T) + 
  geom_line(data = df, aes(x=time, y=E)) 

but this is throwing errors about 'metric' not being found when adding the geom_line. Is there a way of fixing this?

The other way of fixing this could be to include E in the pivot_longer operation (it's all from the same dataset), then somehow restrict the geom_area plot only to groups A-D, and restric the line to only group E. Could this work?


Solution

  • Ok - sorted.

    My second hunch was correct: pivotting all columns (A-E), then setting restrictions in the data parameter of each of the plots has done the trick:

    df_long <- df %>% pivot_longer(cols = c('A', 'B', 'C', 'D', 'E'), names_to='metric', values_to='value')
    
    ggplot(df_long, aes(x=time, y=value, fill=metric)) + 
      geom_area(data = df_long[df_long$metric!='E'], alpha=0.6 , linewidth=0.5, colour="white") +
      scale_fill_viridis(discrete = T) + 
      geom_line(data = df_long[df_long$metric=='E'], aes(x=time, y=value))