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
As already pointed out, this is problematic because the plots you want to merge have such different y-scales. You can try
to get
Although a bit late... Another version which is working with preset bins:
(Only the second y-axis is not working yet...)
Also a bit late, here's another solution that extends @Christoph 's Solution with a second y-Axis.
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.
you can try a ggplot approach with a second axis
There are two ways to go about this. One is to ignore the different scales and use relative frequency in your histogram. This results in a harder to read histogram. The second way is to alter the scale of one or the other element.
I suspect this question will soon become interesting to you, particularly @hadley 's answer.
ggplot2 single scale
Here is a solution in
ggplot2
. I am not sure you will be satisfied with the outcome though because the CDF and histograms (count or relative) are on quite different visual scales. Note this solution has the data in a dataframe calledmydata
with the desired variable inx
.base R multi scale
Here I will rescale the empirical CDF so that instead of a max value of 1, its maximum value is whatever bin has the highest relative frequency.