Feng Tian
Feng Tian

Reputation: 1589

How to reverse the stacking order in stacked area graph using ggplot2

enter image description hereI want to plot stacked area graph using ggplot2, but I found my result is different from that in the book (R Graphics Cookbook Figure 4-22)

library(gcookbook)

library(plyr)

ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup, order=desc(AgeGroup))) + geom_area(colour="black", size=.2, alpha=.4) + scale_fill_brewer(palette="Blues")

The stacking order could not be reversed (In the book, the ">64" should be in the bottom). Is there something wrong in this process?

Upvotes: 3

Views: 1148

Answers (1)

Qaswed
Qaswed

Reputation: 3889

An adhoc approach is to reorder you data. Instead of

AgeGroup 
      <5     
    5-14    
   15-24

you want

AgeGroup 
>64     
55-64  
45-54

So you could take the last element and put it in first place, the second last element in second place, ... Something similar to c("A", "B", "C", "D")[4:1] happens when you use

swap <- uspopage[nrow(uspopage):1,] 
ggplot(swap, aes(x=Year, y=Thousands, fill=AgeGroup, order=desc(AgeGroup))) + 
geom_area(colour="black", size=.2, alpha=.4) + scale_fill_brewer(palette="Blues")

2016-06-02: I gave some explanation after request in comment.

Upvotes: 2

Related Questions