r - ggplot2 中的密度图和直方图

标签 r ggplot2 density-plot

我有以下数据框

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

我想将密度图叠加到直方图上,但它看起来像 0 中的一条细线

enter image description here

最佳答案

您需要获取 geom_histogramgeom_density共享同一轴。在这种情况下,我通过添加 aes(y=..density) 指定两者都针对密度进行绘图。期限到 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)

enter image description here

正如最初指定的那样,美学 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)

enter image description here

关于r - ggplot2 中的密度图和直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61548507/

相关文章:

r - 在 ggplot 中制作带有 x 轴垂直标签的条形图

r - 使用 dplyr/ggplot 函数在 for 循环中调用多个变量

r - ggplot 中多个组的密度图

r - R 中离散数据的计算密度

r - 如何使用plot.xts在蜡烛图中设置蜡烛的宽度?

r - 如何使用 knitr 比较不同版本 R 的性能?

R,使用scale_linetype_manual更改ggplot图例名称

r - 缺少参数 "env",没有默认的 qplot 或 ggplot R

R - 扩展多维数组

从字符串中删除第 n 个空格