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:

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!
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))

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))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With