Question

I would like to add error bars on a stacked area graph created with ggplot2.

My csv file looks like :

Day  Cat  Val   Error  
0    A    0     0.00  
0    B   44.77  1.16  
0    C   54.64  0.88  
13   A   1.34   0.32  
13   B   22.78  0.45  
13   C   38.33  2.12  
19   A   1.95   0.35  
19   B   24.00  2.25  
19   C   40.30  3.86

I tried this :

ggplot(data=mydata, aes(x=Day,y=Val, group=Cat, fill=Cat,colour=Cat, ymax=Val + Error,   ymin= Val - Error)) +
 geom_area() +
 geom_errorbar(width=.5, color="black")

And I had this :

enter image description here

I'm happy with the area chart part of the graph but errors bars are not stacked on data points.

I just getting started with R and I really don't know what the problem is.

Besides, I've found this tip that use geom_segment to avoid overlapping between bars, but I failed to use it with this code.

Thanks for helping me !

Was it helpful?

Solution

You are stacking your data but not your errorbars. To calculate the stacked version of the ymin and ymax of the errorbars you can use the ddply function of the plyr package.

library(plyr) 
mydata2 <- ddply(mydata,.(Day),transform,ybegin = cumsum(Val) - Error,yend = cumsum(Val) + Error)   

ggplot(data=mydata2, aes(x=Day,y=Val, fill=Cat)) +
     geom_area() +
     geom_errorbar(aes(ymax=ybegin , ymin= yend ),width=.5, color="black") 

Output:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top