簡體   English   中英

將密度曲線擬合到 R 中的直方圖

[英]Fitting a density curve to a histogram in R

R 中有一個函數可以擬合直方圖的曲線嗎?

假設您有以下直方圖

hist(c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))

它看起來很正常,但它是歪斜的。 我想擬合一條扭曲的正常曲線來環繞這個直方圖。

這個問題相當基礎,但我似乎無法在互聯網上找到 R 的答案。

如果我正確理解你的問題,那么你可能想要一個密度估計值和直方圖:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

很久以后編輯:

這是一個稍微打扮的版本:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

連同它產生的圖表:

在此處輸入圖片說明

使用 ggplot2 做這件事很容易

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

或模仿德克解決方案的結果

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()

這是我的做法:

foo <- rnorm(100, mean=1, sd=2)
hist(foo, prob=TRUE)
curve(dnorm(x, mean=mean(foo), sd=sd(foo)), add=TRUE)

一個額外的練習是用 ggplot2 包來做到這一點......

Dirk解釋了如何在直方圖上繪制密度函數。 但有時您可能希望采用偏態正態分布的更強假設並繪制該分布而不是密度。 您可以估計分布的參數並使用sn 包繪制它:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

偏態正態分布數據圖

這可能對更偏斜正常的數據更有效:

另一個偏態正態圖

我遇到了同樣的問題,但 Dirk 的解決方案似乎不起作用。 我每次都收到這個警告信息

"prob" is not a graphical parameter

我通讀了?hist並發現了關於freq: a logical vector set TRUE by default.

對我有用的代碼是

hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)

這是核密度估計,請點擊此鏈接查看概念及其參數的精彩插圖。

曲線的形狀主要取決於兩個元素:1)通過輸入和加權所有數據,為 x 坐標中的每個值估計 y 坐標中的一個點的內核(通常是Epanechnikov 或 Gaussian ); 它是對稱的,通常是積分為一個的正函數; 2)帶寬,越大曲線越平滑,越小曲線越擺動。

對於不同的需求,應該應用不同的包,你可以參考這個文檔: R中的密度估計 對於多元變量,您可以轉向多元核密度估計

一些評論要求將密度估計線縮放到直方圖的峰值,以便 y 軸保持為計數而不是密度。 為了實現這一點,我編寫了一個小函數來自動拉取最大 bin 高度並相應地縮放密度函數的 y 維度。

hist_dens <- function(x, breaks = 15, main = "title", xlab = "x", ylab = "y") {
  
  dens <- density(x, na.rm = T)
  
  raw_hist <- hist(x, breaks = breaks, plot = F)
  
  scale <- max(raw_hist$counts)/max(raw_hist$density)
  
  hist(x, breaks = breaks, prob = F, main = main, xlab = xlab, ylab = ylab)
  
  lines(list(x = dens$x, y = scale * dens$y), col = "red", lwd = 2)
  
}

hist_dens(rweibull(200, 1), breaks = 25)

reprex 包(v2.0.1) 於 2021 年 12 月 14 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM