2014-12-26 2 views
6

히스토그램에 농도 선 (실제로 일반 밀도)을 추가하고 싶습니다.ggplot2의 카운트 데이터가있는 막대 그래프에 밀도 선 추가

다음 데이터가 있다고 가정합니다.

set.seed(123)  
df <- data.frame(x = rbeta(10000, shape1 = 2, shape2 = 4)) 

ggplot(df, aes(x = x)) + geom_histogram(colour = "black", fill = "white", 
             binwidth = 0.01) 

enter image description here

내가 사용 밀도 라인을 추가 할 수 있습니다 : 나는 ggplot2하여 히스토그램을 그릴 수

ggplot(df, aes(x = x)) + 
    geom_histogram(aes(y = ..density..),colour = "black", fill = "white", 
       binwidth = 0.01) + 
    stat_function(fun = dnorm, args = list(mean = mean(df$x), sd = sd(df$x))) 

enter image description here

을하지만이 실제로 원하는 것이 아니다 I 이 밀도 선을 카운트 데이터에 맞추기를 원합니다.

이 문제에 대한 해결책을 제시 한 비슷한 게시물 (HERE)이 있습니다. 하지만 제 경우에는 효과가 없었습니다. 내가 원하는 것을 얻으려면 임의의 확장 요소가 필요합니다. 그리고이 전혀 일반화되지 않습니다 :

ef <- 100 # Expansion factor 

ggplot(df, aes(x = x)) + 
    geom_histogram(colour = "black", fill = "white", binwidth = 0.01) + 
    stat_function(fun = function(x, mean, sd, n){ 
    n * dnorm(x = x, mean = mean, sd = sd)}, 
    args = list(mean = mean(df$x), sd = sd(df$x), n = ef)) 

enter image description here

나는 정규 분포이

  • 처음으로 일반화하는 데 사용할 수있는 모든 단서,
  • 다음 다른 빈 크기에,
  • 그리고 마지막으로 다른 배포본에 도움이 될 것입니다.
+0

가나요? 같은 것을 두 번 업로드 한 것처럼 보입니다 – arvi1000

+0

배포본에 맞게 'MASS' 패키지에'fitdistr (...)'을 사용하십시오. – jlhoward

답변

10

마법을 사용하면 피팅 분배 기능이 작동하지 않습니다. 명시 적으로해야합니다. 한 가지 방법은 MASS 패키지에 fitdistr(...)을 사용하는 것입니다. 영업 이익의 의견에 응답 :

# mediocre fit - also not surprising... 
ggplot(df, aes(x = x)) + 
    geom_histogram(aes(y=..density..),colour = "black", fill = "white", binwidth = 0.01)+ 
    stat_function(fun=dgamma,args=fitdistr(df$x,"gamma")$estimate) 

편집

# horrible fit - no surprise here 
ggplot(df, aes(x = x)) + 
    geom_histogram(aes(y=..density..),colour = "black", fill = "white", binwidth = 0.01)+ 
    stat_function(fun=dnorm,args=fitdistr(df$x,"normal")$estimate) 

library(MASS) # for fitsidtr(...) 
# excellent fit (of course...) 
ggplot(df, aes(x = x)) + 
    geom_histogram(aes(y=..density..),colour = "black", fill = "white", binwidth = 0.01)+ 
    stat_function(fun=dbeta,args=fitdistr(df$x,"beta",start=list(shape1=1,shape2=1))$estimate) 

.

배율 인수는 binwidth & # x2715; 표본의 크기. 두 차트 이미지가 동일하게 당신은 의미

ggplot(df, aes(x = x)) + 
    geom_histogram(colour = "black", fill = "white", binwidth = 0.01)+ 
    stat_function(fun=function(x,shape1,shape2)0.01*nrow(df)*dbeta(x,shape1,shape2), 
       args=fitdistr(df$x,"beta",start=list(shape1=1,shape2=1))$estimate) 

+1

다른 배포판에 대한 일반화에 감사드립니다. 나의 궁극적 인 목표는이 선을 밀도가 아닌 개수 데이터에 맞추는 것입니다. 어떻게하는지에 대한 통찰력이 있습니까? (원래 게시물의 세 번째 줄거리와 동일한 줄거리를 원합니다.) – HBat

+1

위의 편집 내용을 참조하십시오. – jlhoward

+0

수식 (0.01 * nrow (df) * dbeta (x, shape1, shape2))의 '0.01'값은 다른 binwidth 또는 샘플 크기로 일반화 할 수 없습니다.샘플 크기가 2474 (10000 대신)이고 0.03 (0.01 대신)이라고 가정합니다. 0.01은 빈 너비와 샘플 크기의 함수 여야한다고 생각합니다. – HBat