簡體   English   中英

ggplot混合模型R

[英]ggplot mixture model R

我有一個包含數值和分類變量的數據集。 每個類別的數值變量的分布都不同。 我想為每個分類變量繪制“密度圖”,以便它們在視覺上低於整個密度圖。

這類似於沒有計算混合模型的混合模型的組件(因為我已經知道分割數據的分類變量)。

如果我根據分類變量將 ggplot 分組,則四個密度中的每一個都是真實密度並集成為一個。

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

在此處輸入圖片說明

我想要的是將每個類別的密度作為子密度(不整合為 1)。 類似於下面的代碼(我只為三種鳶尾中的兩種實現了)

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 做到這一點? 還是去計算?

謝謝你的想法。

你的意思是這樣的嗎? 不過,您需要更改比例。

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

暫無
暫無

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

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