2012-12-19 150 views
15

我想補充的密度曲線,直方圖和culumative直方圖,這樣的 -添加密度線,以直方圖和累積直方圖

enter image description here

下面是據我可以去:

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") 
+0

「密度」與「頻率」不在相同的範圍內。我敢肯定你會在SO中找到有效的例子,如果你只是做更多的搜索。你在發佈之前做過搜索,對嗎? –

+0

你需要多少副本? 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-over-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-the-of-histogram –

+0

@DWin謝謝你的建議,我已經看到了所有這些,但我無法弄清楚如何覆蓋累積密度曲線和規則密度曲線... – jon

回答

23

提供無解釋:

## 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