如何在 R 中的直方图上绘制 SD 的钟形曲线?

How to draw bell curve of SD over a histogram in R?

我正在尝试弄清楚如何可视化年龄直方图的标准偏差。在 CODE 1 中提供了年龄与频率的直方图。请注意,频率代表直方图中的人数(即大约 550 人年龄在 70-75 岁之间)。然而,我想要可视化它的方式是提供 CODE 2,但请注意直方图显示的是密度而不是频率。当我尝试 CODE 3 时,钟形曲线是平坦的。有人知道如何解决这个问题吗?

代码 1:

#PROVIDE HISTOGRAMS OF AGE AND TOTAL.DAYS.IN.HOSPITAL
hist(
  dataset15$Age, las=1,
  main="Histogram of Age", xlab="AGE", ylab="Number of patients",
  xlim = c(0,100), ylim = c(0,600),
  xaxp = c(0,100,10), yaxp=c(0,600,24)
)

代码 2:

hist(dataset15$Age, freq=F, breaks=12)
lines(
  seq(10, 100, by=.5), 
  dnorm(seq(10, 100, by=.5),
  mean(dataset15$Age), 
  sd(dataset15$Age)), 
  col="blue"
)

代码 3:

#PROVIDE HISTOGRAMS OF AGE AND TOTAL.DAYS.IN.HOSPITAL
hist(
  dataset15$Age, las=1,
  main="Histogram of Age", xlab="AGE", ylab="Number of patients",
  xlim = c(0,100), ylim = c(0,600),
  xaxp = c(0,100,10), yaxp=c(0,600,24)
)
lines(
  seq(0, 100, by=.5), 
  dnorm(seq(0, 100, by=.5),
  mean(dataset15$Age), sd(dataset15$Age)), 
  col="blue"
)

输出 1:

输出 2:

输出 3:

正如@Rodrigo 所指出的,您必须将密度缩放到直方图。 请参阅下面的代码。

n <- 2000
age <- rnorm(n, m = 70, sd = 5)


h <- hist(age,
          las=1, breaks = 20,
          main="Histogram of Age", xlab="AGE", ylab="Number of patients",
     xlim = c(0,100), ylim = c(0,600),
     xaxp = c(0,100,10), yaxp=c(0,600,24))

lx <- seq(10, 100, by=.5)
ly <- dnorm(lx, mean(age), sd(age)) * sum(h$counts)/sum(h$density), # here is the magic
lines(x = lx,y = ly,col ="blue") 

输出以下图: