Home > database >  geom_area with a grouping variable spread across multiple columns
geom_area with a grouping variable spread across multiple columns

Time:09-28

Basically my data looks something like this,

Year, group1, group2, group3
1999, 500,    1200,   1700
2000, 700,    3000,   2000
2001, 500,    4500,   2500

I want to have a stacked geom_area chart. If possible, without the use of libraries outside of dplyr

An example of the desired output:

enter image description here

CodePudding user response:

We can do it all within the tidyverse. Use tidyr::pivot_longer to get the data in the right format, with a value variable and a grouping variable(here "name"). Use ggplot with the fill aesthetic mapped to the grouping variable.

library(dplyr)
library(ggplot2)
library(tidyr)

df %>% pivot_longer(!Year)%>%
ggplot(aes(x=Year, y=value, fill=name)) 
geom_area()

enter image description here

  • Related