r : ecdf over histogram

JuanPablo picture JuanPablo · Mar 26, 2015 · Viewed 7.7k times · Source

in R, with ecdf I can plot a empirical cumulative distribution function

plot(ecdf(mydata))

and with hist I can plot a histogram of my data

hist(mydata)

How I can plot the histogram and the ecdf in the same plot?

EDIT

I try make something like that

https://mathematica.stackexchange.com/questions/18723/how-do-i-overlay-a-histogram-with-a-plot-of-cdf

Answer

symbolrush picture symbolrush · Oct 18, 2016

Also a bit late, here's another solution that extends @Christoph 's Solution with a second y-Axis.

par(mar = c(5,5,2,5))
set.seed(15)
dt <- rnorm(500, 50, 10)
h <- hist(
  dt,
  breaks = seq(0, 100, 1),
  xlim = c(0,100))

par(new = T)

ec <- ecdf(dt)
plot(x = h$mids, y=ec(h$mids)*max(h$counts), col = rgb(0,0,0,alpha=0), axes=F, xlab=NA, ylab=NA)
lines(x = h$mids, y=ec(h$mids)*max(h$counts), col ='red')
axis(4, at=seq(from = 0, to = max(h$counts), length.out = 11), labels=seq(0, 1, 0.1), col = 'red', col.axis = 'red')
mtext(side = 4, line = 3, 'Cumulative Density', col = 'red')

Histogram with CDF, two scales and two y-axes

The trick is the following: You don't add a line to your plot, but plot another plot on top, that's why we need par(new = T). Then you have to add the y-axis later on (otherwise it will be plotted over the y-axis on the left).

Credits go here (@tim_yates Answer) and there.