2

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 !

Community
  • 1
  • 1

1 Answers1

1

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

Jonas Tundo
  • 6,137
  • 2
  • 35
  • 45
  • Thank you for the code! It works with my data but I get 4 times this error message : Removed 2 rows containing missing values (geom_path). I think it appears because the Error column contains few 0. – Mini Kitkat Apr 18 '13 at 08:00
  • A Warning message I think (I use a French version of R) – Mini Kitkat Apr 18 '13 at 12:02