r:直方图上的ecdf [英] r : ecdf over histogram
问题描述
在R中,用ecdf
可以绘制经验累积分布函数
in R, with ecdf
I can plot a empirical cumulative distribution function
plot(ecdf(mydata))
并使用hist
可以绘制数据的直方图
and with hist
I can plot a histogram of my data
hist(mydata)
如何在同一图中绘制直方图和ecdf?
How I can plot the histogram and the ecdf in the same plot?
我尝试做类似的事情
https://mathematica .stackexchange.com/questions/18723/如何用cdf图覆盖直方图
推荐答案
还有点晚了,这是另一个解决方案,它用第二个y轴扩展了@Christoph的解决方案.
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')
诀窍如下:您无需在绘图上添加线,而是在顶部绘制另一个绘图,这就是为什么我们需要par(new = T)
的原因.然后,您必须稍后添加y轴(否则它将在左侧的y轴上绘制).
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.
这篇关于r:直方图上的ecdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!