R重叠正态曲线到概率直方图

R overlap normal curve to probability histogram

在 R 中,我可以将正态曲线与密度直方图重叠: 最终我可以将密度直方图转换为概率图:

a <- rnorm(1:100)
test <-hist(a,  plot=FALSE)
test$counts=(test$counts/sum(test$counts))*100   # Probability
plot(test, ylab="Probability")
curve(dnorm(x, mean=mean(a), sd=sd(a)), add=TRUE)

但是我不能再与正态曲线重叠,因为它超出了比例。

有解决办法吗?也许是第二个 Y 轴

首先你应该保存你的rnorm数据,否则你每次都会得到不同的数据。

seed = rnorm(100)

接下来继续

hist(seed,probability = T)
curve(dnorm(x, mean=mean(na.omit(seed)), sd=sd(na.omit(seed))), add=TRUE)

现在你得到了预期的结果。带密度曲线的直方图。

现在我的问题很清楚了。事实上,第二个 y 轴似乎是最好的选择,因为这两个数据集的尺度完全不同。

为了做到这一点,你可以这样做:

set.seed(2)
a <- rnorm(1:100)
test <-hist(a,  plot=FALSE)
test$counts=(test$counts/sum(test$counts))*100   # Probability
plot(test, ylab="Probability")
#start new graph
par(new=TRUE)
#instead of using curve just use plot and create the data your-self
#this way below is how curve works internally anyway
curve_data <- dnorm(seq(-2, 2, 0.01), mean=mean(a), sd=sd(a))
#plot the line with no axes or labels
plot(seq(-2, 2, 0.01), curve_data, axes=FALSE, xlab='', ylab='', type='l', col='red' )
#add these now with axis
axis(4, at=pretty(range(curve_data)))

输出:

y 轴不是您标记的 "probability"。是计数数据。如果将直方图转换为概率,应该没有问题:

x <- rnorm(1000)
hist(x, freq= FALSE, ylab= "Probability")
curve(dnorm(x, mean=mean(x), sd=sd(x)), add=TRUE)