Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting cumulative histogram with negative and positive side in ggplot?

R version 3.1.1 (2014-07-10) Platform: i386-w64-mingw32/i386 (32-bit)

I am working on a histogram with ggplot2. The aim is to have a cumulative histogram for the negative and positive side combined in one plot. Easily I can plot the histograms separately for the negative and positive side, but as soon as I combine them, it becomes a mess.

Sample Data:

df <- structure(list(NEG = c(-42.962, -1.86, -13.275, -56.188, -2.25, 
-12.199, -3.953, -13.309, -4.512, -11.461, -19.813, -54.311, 
-59.934, -7.045, -14.44, -40.829, -143.034, -233.009, -70.72, 
-5.578), POS = c(180.328, 290.809, 156.894, 31.414, 629.74, 590.672, 
268.89, 69.618, 415.007, 138.444, 10.139, 20.565, 106.027, 69.129, 
19.809, 8.22, 53.711, 36.035, 11.694, 12.705)), .Names = c("NEG", 
"POS"), row.names = c(NA, 20L), class = "data.frame")

Code for positive side does work:

ggplot(df)+ 
      geom_histogram(aes(x= POS, y=rev(cumsum(rev(..count..)))/4),binwidth=1)

Code for negative side does work too:

ggplot(df)+ 
      geom_histogram(aes(x= NEG, y=cumsum(..count..)/4),binwidth=1)

But combining these two layers produces a mess:

ggplot(df)+ 
      geom_histogram(aes(x= POS, y=rev(cumsum(rev(..count..)))/4),binwidth=1)+
      geom_histogram(aes(x= NEG, y=cumsum(..count..)/4),binwidth=1)

I hope you can help me!

Thanks a lot!

like image 661
VDK Avatar asked Jan 07 '15 13:01

VDK


1 Answers

The problem is that for both layers the cumulative sum is calculated over the whole x-axis.

ggplot(df)+ 
  geom_histogram(aes(x= POS, y=ifelse(x>=0, 
                                      rev(cumsum(rev(..count..)))/4, 
                                      0)),
                 binwidth = 1)+ 
  geom_histogram(aes(x= NEG, y=ifelse(x<=0,
                                      cumsum(..count..)/4,
                                      0)),
                 binwidth = 1)

resulting plot

like image 108
Roland Avatar answered Sep 20 '22 10:09

Roland