2017-10-09 123 views
1

我正嘗試使用ggridges包(基於ggplot2)創建一個joyplot。一般的想法是,一張快樂圖創建很好的縮放堆積密度圖。但是,我似乎無法使用加權密度來生成其中的一個。是否有某種方法將抽樣權重(用於加權密度)合併到創建Joyplot中的密度計算中?R:加權Joyplot/Ridgeplot /密度圖?

下面是ggridges包的文檔鏈接:https://cran.r-project.org/web/packages/ggridges/ggridges.pdf我知道很多基於ggplot的包可以接受額外的美學,但我不知道如何爲這種類型的geom添加權重。

此外,這裏是ggplot中未加權的joyplot的示例。我試圖將其轉換爲加權圖,密度按照權重進行加權。

# Load package, set seed 
library(ggplot) 
set.seed(1) 

# Create an example dataset 
dat <- data.frame(group = c(rep("A",100), rep("B",100)), 
        pweight = runif(200), 
        val = runif(200)) 

# Create an example of an unweighted joyplot 
ggplot(dat, aes(x = val, y = group)) + geom_density_ridges(scale= 0.95) 
+0

如果您提供樣本輸入數據的[可重現示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),則更容易幫助您。 – MrFlick

+0

增加了一個可重現的例子,每@MrFlick – user3614648

回答

4

它看起來像要做到這一點的方法是使用stat_density而不是默認的stat_density_ridges。根據您鏈接到的文檔:

請注意,默認stat_density_ridges會對所有數據集進行聯合密度估計。這在使用分面圖時可能不會生成所需的 結果。作爲替代方案,您可以將 stat = "density"設置爲使用stat_density。在這種情況下,需要 添加美學映射height = ..density..(請參閱示例)。

幸運的是,stat_density(不像stat_density_ridges)理解的美學weight,並將它傳遞給底層density電話。你最終的東西,如:

ggplot(dat, aes(x = val, y = group)) + 
    geom_density_ridges(aes(height=..density.., # Notice the additional 
          weight=pweight),  # aes mappings 
         scale= 0.95, 
         stat="density") # and use of stat_density 

..density..變量由stat_density自動生成。

注:看來,當您使用stat_density x軸範圍的行爲有點不同:它會修剪密度圖的數據範圍和下降好看的尾巴。您可以通過手動擴展x軸來輕鬆修正此問題,但我認爲這值得一提。

+0

這非常有幫助,謝謝!你能夠證明這個例子是如何工作的嗎? – aeongrail