簡體   English   中英

密度 plot 和 ggplot2 中的直方圖

[英]Density plot and histogram in ggplot2

我有以下數據框

        x1<-data.frame(n = rnorm(1000000, mean=0, sd=1), nombre= "x1")

        x2<-data.frame(n=rnorm(1500000, mean=3, sd=1), nombre= "x2")

        x<-rbind(x1, x2)

        ggplot(x, aes(n, fill=nombre))+
          geom_histogram(alpha=0.5, binwidth=0.25, position = "identity")+
          geom_density()

我想將密度 plot 疊加到直方圖上,但它看起來就像 0 中的細線

在此處輸入圖像描述

您需要讓geom_histogramgeom_density共享同一軸。 在這種情況下,我通過將aes(y=..density)項添加到 geom_histogram 來針對密度指定geom_histogram 還要注意一些不同的美學以避免過度繪制,以便我們能夠更清楚地看到兩個幾何:

ggplot(x, aes(n, fill=nombre))+
    geom_histogram(aes(y=..density..), color='gray50',
        alpha=0.2, binwidth=0.25, position = "identity")+
    geom_density(alpha=0.2)

在此處輸入圖像描述

正如最初指定的那樣,美學fill=適用於兩者,因此您有直方圖和密度幾何顯示您根據“x1”和“x2”分組的分布。 如果您想要 x1 和 x2 的組合集的密度幾何,只需為直方圖幾何指定fill=美學:

ggplot(x, aes(n))+
    geom_histogram(aes(y=..density.., fill=nombre),
        color='gray50', alpha=0.2,
        binwidth=0.25, position = "identity")+
    geom_density(alpha=0.2)

在此處輸入圖像描述

我想出了一個想法,允許您根據直方圖縮放密度 plot。

您可以使用stat:density function 獲取密度數據並手動縮放它們,然后使用geom_line plot 它們:

ggplot(x, aes(n, fill=nombre))+
  geom_histogram(alpha=0.5, binwidth=0.25, position = "identity") +
  geom_line(aes(x,y, group=nombre),
    ~ .x %>% group_by(nombre) %>%
      mutate(n_cut = cut(n, seq(min(n), max(n), 0.25))) %>% 
      summarize(
        y = density(n)$y * max(table(n_cut)) / max(density(n)$y),
        x = density(n)$x
      )
  )

結果

暫無
暫無

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

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