밀도 곡선을 R의 히스토그램에 장착합니다
-
19-09-2019 - |
문제
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()
또는 Dirk의 솔루션에서 결과를 모방합니다
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 패키지로 이것을하는 것입니다 ...
단도 히스토그램을 통해 밀도 함수를 플로팅하는 방법을 설명했습니다. 그러나 때때로 당신은 비뚤어진 정규 분포의 더 강한 가정과 밀도 대신에 그것을 음모로 가고 싶을 수도 있습니다. 분포의 매개 변수를 추정하고 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)
제휴하지 않습니다 StackOverflow