Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Order of stacked areas with ggplot geom_area

Tags:

r

ggplot2

I needed to reinstall R and I now encounter a little problem with ggplot. I am sure there is a simple solution to it and I appreciate all hints!

I am using the stacked area plot quite often, and usually I got the desired stacking and legend order by defining the factor levels and plotting in reverse order. However, this is not working any more after the re-installation.

Here is an example:

dx <- data.frame(x=rep(1:8,3),y=rep(c(2,3,2,4,3,5,3,2),3),z=c(rep("bread",8),rep("butter",8),rep("fish",8)))

ggplot() + geom_area(data=dx, aes(x=x, y=y, fill=z, order=-as.numeric(z)))

This gives the following plot:

enter image description here

It looks as if "order" did not have any impact on the plot.

The desired plot would stack the areas as shown in the legend, i.e. red area on top, blue area at the bottom.

Where is my mistake?

Many thanks in advance!

like image 371
Aki Avatar asked Oct 26 '25 12:10

Aki


1 Answers

You can either use (the colors will also be reversed):

dx$z <- factor(dx$z, levels = rev(levels(dx$z)))
ggplot() + geom_area(data=dx, aes(x=x, y=y, fill=z))

enter image description here

Or directly use this (without reversing the factor levels, which won't change the color):

ggplot() + geom_area(data=dx, aes(x=x, y=y, fill=z)) + 
                 guides(fill = guide_legend(reverse=TRUE))

enter image description here

like image 103
Sumedh Avatar answered Oct 28 '25 03:10

Sumedh