web-dev-qa-db-ja.com

ヒストグラムと累積ヒストグラムに密度線を追加します

次のように、ヒストグラムと累積ヒストグラムに密度曲線を追加したいと思います。

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")
16
jon

説明なしで提供:

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

23
Josh O'Brien