Home > Net >  Set order of stacked area graphs by sales in ggplot R
Set order of stacked area graphs by sales in ggplot R

Time:04-30

could you tell me how to order stacked charts from top to down according to sales in 2013? For instance, in 2013 sales were the highest in D group so I want to be in this category always at the top and so on.

df <- data.frame (Year  = c("2010", "2010",  "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
                  Sale = c(100,200,50,500,400,200,400,145,100,456,345,321,100,200,250,400),
                 Group = c("A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D"))

df$Year <- as.integer(df$Year)



ggplot(df, aes(x = Year, y = Sale, fill = Group))  
  geom_area()

enter image description here

CodePudding user response:

You need to use fct_reorder() from forcats to reorder the factor Group by Sale:

df %>% 
  mutate(Group = fct_reorder(Group, desc(Sale))) %>% 
  ggplot(aes(x = Year, y = Sale, fill = Group))  
  geom_area()

enter image description here

To do it by a specific year, I did the following.

ls <- df %>% filter(Year == 2013) %>% arrange(desc(Sale)) %>% select(Group)
df$Group <- factor(df$Group, levels = ls$Group)

df %>% 
  ggplot(aes(x = Year, y = Sale, fill = Group))  
  geom_area()

Which was a manual reorder.

  • Related