Mirza Hashim
Mirza Hashim

Reputation: 79

R - Stacked Area chart

For the given data set how can i generate a stacked area chart Inflow vs. Date across different Sources in such a fashion that the maximum total inflow source is closest to the X (Date) axis and the least inflow source the farthest.

Date    Source  Inflow  
1/1/06  s1       271   
1/1/06  s3       368  
1/1/06  s2       425  
1/2/06  s4       580  
1/2/06  s2       233  
1/2/06  s3       243  
1/2/06  s1       428  
1/3/06  s5       164  
1/3/06  s2       461  
1/3/06  s3       180  
1/4/06  s1       258  
1/4/06  s2       153  
1/5/06  s6       443 

ggplot(data, aes(x=Inflow, y=Date, fill=Source)) + geom_area(colour="black", size=.2, alpha=.4) + scale_fill_brewer(palette="Greens", breaks=rev(levels(data$Source)))

Please find the attached Plot

Upvotes: 0

Views: 130

Answers (1)

giocomai
giocomai

Reputation: 3518

Honestly, stacked area chart does not make much sense with the data you provide, as some categories are found on a single day (so there is nowhere for the area to expand, hence the vertical lines).

Stacked bar chart may be the way to go.

library("tidyverse")


records <- tribble(~Date, ~Source, ~Inflow, 
        "1/1/06",  "s1",      271,   
        "1/1/06",  "s3",      368,  
        "1/1/06",  "s2",      425,  
        "1/2/06",  "s4",      580,  
        "1/2/06",  "s2",      233,  
        "1/2/06",  "s3",      243,  
        "1/2/06",  "s1",      428,  
        "1/3/06",  "s5",      164,  
        "1/3/06",  "s2",      461,  
        "1/3/06",  "s3",      180,  
        "1/4/06",  "s1",      258,  
        "1/4/06",  "s2",      153,  
        "1/5/06",  "s6",      443)

records %>% 
  mutate(Date = as.Date(lubridate::mdy(Date))) %>% 
  ggplot(mapping = aes(x=Date, y=Inflow, fill=Source)) +
  geom_area(colour="black", size=.2, alpha=.4, position = position_stack()) +
  scale_fill_brewer(palette="Greens")

records %>%  
  mutate(Date = as.Date(lubridate::mdy(Date))) %>% 
  ggplot(mapping = aes(x=Date, y=Inflow, fill=Source)) +
  geom_col(colour="black", size=.2, alpha=.4, position = position_stack()) +
  scale_fill_brewer(palette="Greens")

Upvotes: 3

Related Questions