16

I want to add density curve to histogram and cumulative histogram, like this:

enter image description here

Here is as far I can go:

hist.cum <- function(x, plot=TRUE, ...){
  h <- hist(x, plot=FALSE, ...)
  h$counts <- cumsum(h$counts)
  h$density <- cumsum(h$density)
  h$itensities <- cumsum(h$itensities)
  if(plot)
    plot(h)
  h
}
 x <- rnorm(100, 15, 5)
hist.cum(x)
 hist(x, add=TRUE, col="lightseagreen")

 #
lines (density(x), add = TRUE, col="red")
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jon
  • 11,186
  • 19
  • 80
  • 132
  • `density` is not on the same scale as `frequency`. I'm pretty sure you will find worked examples in SO if you do just a bit more searching. You did search SO before posting , right? – IRTFM Dec 19 '12 at 21:27
  • How many duplicates do you need? http://stackoverflow.com/questions/5688082/ggplot2-overlay-histogram-with-density-curve http://stackoverflow.com/questions/9246040/axis-labeling-in-r-histogram-and-density-plots-multiple-overlays-of-density-plots http://stackoverflow.com/questions/1497539/fitting-a-density-curve-to-a-histogram-in-r http://stackoverflow.com/questions/12945951/r-programming-how-to-plot-a-density-estimate-on-top-of-the-histogram – IRTFM Dec 20 '12 at 02:40
  • 2
    @DWin Thank you for the suggestion, I have seen all of them but I could not figure out how to overlay both cumulative and regular density curve ... – jon Dec 20 '12 at 02:53

1 Answers1

23

Offered without explanation:

## Make some sample data
x <- sample(0:30, 200, replace=T, prob=15 - abs(15 - 0:30))

## Calculate and plot the two histograms
hcum <- h <- hist(x, plot=FALSE)
hcum$counts <- cumsum(hcum$counts)
plot(hcum, main="")
plot(h, add=T, col="grey")

## Plot the density and cumulative density
d <- density(x)
lines(x = d$x, y = d$y * length(x) * diff(h$breaks)[1], lwd = 2)
lines(x = d$x, y = cumsum(d$y)/max(cumsum(d$y)) * length(x), lwd = 2)

enter image description here

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455