4

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!

Aki
  • 409
  • 2
  • 6
  • 15

2 Answers2

8

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

Sumedh
  • 4,835
  • 2
  • 17
  • 32
  • 1
    Thank you very much for your solution. Actually the problem was that the _order_ aesthetic no longer exists. This causes me some troubles, since defining the factor levels alone was not enough. See this [post](http://stackoverflow.com/questions/15251816/how-do-you-order-the-fill-colours-within-ggplot2-geom-bar) for a detailed explanation. – Aki Jul 18 '16 at 13:51
0

This is a great working example for newcomers. The main thing I was missing is the option to place the series one after the other, instead of stacking them.

  • position = "stack" (Default)
  • position = "dodge"
 geom_area(position = "dodge")
samandrew
  • 1
  • 1