Chirag Shekhar Chirag Shekhar - 2 months ago 16
R Question

How to obtain a stacked area plot for a categorized data frame?

I just started exploring ggplot2, and I currently don't have an understanding of the aes objects it uses so frequently. I've tried several approaches to solving this problem, but it hasn't been working. Any help would be much appreciated!

So, I have a data frame that I've classified specifically for the purpose of plotting, which looks something like this:

> ggplotframe[1:8,]
gamma weights assets
1 0.002 0.25 1
2 0.002 0.25 2
3 0.002 0.25 3
4 0.002 0.25 4
5 0.004 0.25 1
6 0.004 0.25 2
7 0.004 0.25 3
8 0.004 0.25 4

Now, I want to plot a stacked area chart, displaying the
for each
, as the
varies. Since there are 4 assets in this example, there are 4 different weights for each value of gamma, one for each asset, and they are tested over hundreds of such values.

Now, of the approaches I have tried, one is:

gg <- ggplot(ggplotframe, aes(x=gamma, y=weights))
gg <- gg + geom_area(aes(colour=assets, fill=assets))

But in this case, the console flashes the error:
Error in f(...) : Aesthetics can not vary with a ribbon
. How can I resolve this issue?


You don't necessarily have to turn the assets column into a factor, simply wrapping factor around fill in the geom_area will suffice.

gg <- ggplot(ggplotframe, aes(x=gamma, y=weights))
gg <- gg + geom_area(aes(colour=assets, fill=factor(assets)))