ggplot2-创建相对于总样本大小的堆积密度图

问题描述 投票:0回答:2

假设我们有两个样本量不同的组“ a”和“ b”。

n = 10000
set.seed(123)
dist1 = round(rnorm(n, mean = 1, sd=0.5), digits = 1)
dist2 = round(rnorm(n/10, mean = 2, sd = 0.2), digits = 1)
df = data.frame(group=c(rep("a", n), rep("b", n/10)), value=c(dist1,dist2))

我想将下面的堆积图转换成堆积密度图。

library(ggplot2)
ggplot(data=df, aes(x=value, y=(..count..)/sum(..count..), fill=group)) +
  geom_bar()

enter image description here

我知道密度图有一个选项position="stack"。但是,结果如下所示,因为密度的高度是相对于组样本大小,而不是总样本大小。因此,从某种程度上来说,这一小群体的代表人数过多。

ggplot(data=df, aes(x=value, fill=group)) +
  geom_density(position="stack")

enter image description here

是否有一种方法可以创建与上述小节相对应的密度图?

r ggplot2 density-plot
2个回答
1
投票

[密度图与条形图只是做相同的事情,没有给您想要的东西吗?

   ggplot(data=df, aes(x=value, fill=group)) +
     geom_density( aes(y = ..count../sum(..count..)),  position="stack", alpha=.7)

给出

enter image description here


0
投票

如果执行密度图,则y轴与您从第一个直方图获得的轴不同,y轴反映了total上的计数。要获得接近的结果,您可以尝试以下操作,其中直方图函数用于获取计数,转换然后堆叠:

library(dplyr)
library(ggplot2)

RN =range(df$value)

df %>% group_by(group) %>%
do(data.frame(hist(.$value,breaks=seq(RN[1],RN[2],
length.out=40),plot=FALSE)[c("mids","counts")])) %>%
mutate(freq=counts/nrow(df)) %>%
ggplot(aes(x=mids,y=freq,col=group)) + geom_line(position="stack")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.