Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative histogram with ggplot2

Tags:

r

ggplot2

How could I get a cumulative histogram like this

x <- runif(100,0,10)
h <- hist(x)
h[["counts"]] <- cumsum(h[["counts"]])
plot(h)

with ggplot2?

I want also to draw a polygon like this

lines(h[["breaks"]],c(0,h[["counts"]]))

like image 537
Alfredo Sánchez Avatar asked Nov 28 '22 15:11

Alfredo Sánchez


1 Answers

To make cumulative histogram use geom_histogram() and then use cumsum(..count..) for y values. Cumulative line can be added with stat_bin() and geom="line" and y values calculated as cumsum(..count..).

ggplot(NULL,aes(x))+geom_histogram(aes(y=cumsum(..count..)))+
       stat_bin(aes(y=cumsum(..count..)),geom="line",color="green")

enter image description here

like image 76
Didzis Elferts Avatar answered Dec 04 '22 13:12

Didzis Elferts