2016-09-23 2 views
1

숫자 값과 범주 형 변수가있는 데이터 집합이 있습니다. 숫자 변수의 분포는 카테고리마다 다릅니다. 각 범주 형 변수에 대해 "밀도 플롯"을 플롯하여 전체 밀도 플롯보다 시각적으로 낮게 표시하려고합니다.ggplot 혼합물 모델 R

이것은 혼합 모델을 계산하지 않고 혼합 모델의 구성 요소와 비슷합니다 (데이터를 분할하는 범주 형 변수를 이미 알고 있으므로).

범주 변수에 따라 그룹화하려면 ggplot을 사용하면 네 개의 밀도가 각각 실제 밀도가되며 하나에 통합됩니다. 내가 원하는 무엇

library(ggplot2) 
ggplot(iris, aes(x = Sepal.Width)) + geom_density() + geom_density(aes(x = Sepal.Width, group = Species, colour = 'Species')) 

enter image description here

는 하위 밀도 (1 통합되지 않음) 등 각 카테고리의 밀도를하는 것입니다. I 위

enter image description here

결과 (I 단지 세 홍채 종의 두 구현) 다음 코드

myIris <- as.data.table(iris) 
# calculate density for entire dataset 
dens_entire <- density(myIris[, Sepal.Width], cut = 0) 
dens_e <- data.table(x = dens_entire[[1]], y = dens_entire[[2]]) 

# calculate density for dataset with setosa 
dens_setosa <- density(myIris[Species == 'setosa', Sepal.Width], cut = 0) 
dens_sa <- data.table(x = dens_setosa[[1]], y = dens_setosa[[2]]) 

# calculate density for dataset with versicolor 
dens_versicolor <- density(myIris[Species == 'versicolor', Sepal.Width], cut = 0) 
dens_v <- data.table(x = dens_versicolor[[1]], y = dens_versicolor[[2]]) 

# plot densities as mixture model 
ggplot(dens_e, aes(x=x, y=y)) + geom_line() + geom_line(data = dens_sa, aes(x = x, y = y/2.5, colour = 'setosa')) + 
    geom_line(data = dens_v, aes(x = x, y = y/1.65, colour = 'versicolor')) 

에 비슷한는 Y 값을 줄일 수 하드 코딩. ggplot으로 할 수있는 방법이 있습니까? 아니면 그것을 계산?

의견을 보내 주셔서 감사합니다.

답변

1

다음과 같은 것이 있습니까? 당신은 규모를 변경해야합니다.

ggplot(iris, aes(x = Sepal.Width)) + 
    geom_density(aes(y = ..count..)) + 
    geom_density(aes(x = Sepal.Width, y = ..count.., 
       group = Species, colour = Species)) 

또 다른 옵션은

ggplot(iris, aes(x = Sepal.Width)) + 
    geom_density(aes(y = ..density..)) + 
    geom_density(aes(x = Sepal.Width, y = ..density../3, 
        group = Species, colour = Species)) 
+0

안녕을 할 수있다, 그래 그 약속 같은데. 홍채 데이터 세트의 항목 수, 즉 nrow (홍채) = 150으로 크기를 조정하면 꽤 괜찮아 보입니다. ..count .. 대신 .. .. count ../150입니다. 누구든지 이것이 올바른 길인지 확인할 수 있습니까? 필자의 경우 각 카테고리의 숫자는 같지 않지만 데이터의 약 60 %를 차지하는 카테고리가 하나 있습니다. – user3702510

+0

안녕하세요, 그것에 대해 생각하고 토론했으며 올바른 대답입니다. 빠른 답장을 위해 @Kota Mori에게 감사드립니다. y = ..count ../ Number_of_rows_of_entire_dataset을 취하거나 y = ..density ../ number_of_categories를 취하십시오. – user3702510