我试图绘制3个簇中一维数据的相对频率。我想要的是一个直方图,它使用颜色来区分3个聚类,并且我希望每个bin的高度代表特定聚类的该值范围的相对频率。
代码如下:
library(mvtnorm)
library(gtools)
library(ggplot2)
K = 3 # number of clusters
p_p = c(0.25, 0.25, 0.5) # population weights
theta_p = c(2, 5, 15) # population gamma params - shape
phi_p = c(2,2, 5) # population gamma params - scale
N_p = c(25, 25, 50) # sample size within each cluster
set.seed(1) # set seed so that the results are the same each time
y <- numeric()
## We will now sample data from all three clusters
y[1:N_p[1]] <- rgamma(N_p[1], theta_p[1], phi_p[1])
y[(N_p[1]+1): (N_p[1]+N_p[2])] <- rgamma(N_p[2], theta_p[2], phi_p[2])
y[(N_p[1]+N_p[2]+1): sum(N_p)] <- rgamma(N_p[3], theta_p[3], phi_p[3])
Data = data.frame(y = y, source = as.factor(c(rep(1,25), rep(2,25), rep(3,50))))
ggplot(Data, aes(x=y, color = source))+
geom_histogram(aes(y=..count../sum(..count..)),fill="white", position="dodge", binwidth = 0.5) +
theme(legend.position="top")+labs(title="Samples against Theoretical Dist",y="Frequency", x="Sample Value")
length(which(y[1:25]<=0.5))/length(y)
length(which(y[1:25]<=0.5))/length(y[0:25])
现在,我想要的是第一个红色直方图栏的高度等于长度(其中(y [1:25] <= 0.5))/长度(y [0:25])。我会理解我是否正在获取length(which(y [1:25] <= 0.5))/ length(y),我可以解决这个问题。
但是,我得到的高度约为0.12,这两个值都不匹配,让我觉得我完全误解了..count ..和sum(.. count ..)。
答案 0 :(得分:1)
问题不在于您对..count..
的理解,而在于您对binwidth
的工作原理的假设。您假设将其设置为0.5会将中断设置为0、0.5、1、1.5等,但实际上,它将中断设置为数据范围的最小值。因此,实际上,您第一个小节的高度为length(which(y[1:25] <= (min(y) + 0.5)))/length(y)
,即13。
您可以在breaks
中指定geom_histogram
来解决此限制:
ggplot(Data, aes(x = y, color = source)) +
geom_histogram(aes(y = stat(count)/length(y)), fill = "white",
position = "dodge", breaks = seq(0, 6, 0.5)) +
theme(legend.position = "top" +
labs(title = "Samples against Theoretical Dist",
y = "Frequency", x = "Sample Value")
由于矢量为100长,现在每个小节为计数的1/100。