【问题标题】:How to label the mean and three standard deviations on Normal Curve with R如何用R标记正态曲线上的平均值和三个标准差
【发布时间】:2020-09-20 06:15:15
【问题描述】:

我正在尝试在此图上添加均值和 3 sd 作为标签;我已经尝试过“How to plot a normal distribution by labeling specific parts of the x-axis?”,但是那里的解决方案不起作用,因为我有 1000 个观察值。我不能去 label = c(0, 1, 2...mean...500, 501...750) 并且也没有添加三个标准差标签的解决方案。这是情节:

这是我当前的代码:

x = seq(0, 750, length = 1000)
y <- dnorm(x, mean = 435, sd = 72)
plot(x, y,
     type = 'p',
     lwd = 1,
     col = 'red',
     main = "Standard Normal Distribution with Mean 435 and SD 72",
     xlab = "Score",
     ylab = "Frequency"
     )

【问题讨论】:

    标签: r plot


    【解决方案1】:

    也许您可以尝试在代码后添加以下行

    abline(v = 435 + seq(-3,3)*72, col = "black",lty = 2)
    text(435 + seq(-3,3)*72,max(y)/2,c(paste0(-(3:1),"sd"),"mean",paste0(1:3,"sd")))
    

    这样

    【讨论】:

    • 很高兴看到一个紧凑的基础 R 解决方案。 +1
    【解决方案2】:

    您可以使用ggplot2轻松做到这一点。

    library(ggplot2)
    
    df <- data.frame(x, y)
    
    ggplot(df) + 
      geom_point(aes(x, y), color ="red") +
      scale_x_continuous(breaks = 425 + seq(-3 * 72, 3 * 72, 72)) +
      geom_text(aes(x = 425 + seq(-3 * 72, 3 * 72, 72), y = 0.006, 
                label = c("-3 SD", "-2 SD", "-1 SD", "mean", "+1 SD", "+2 SD", "+3 SD"))) +
      geom_vline(xintercept = 425 + seq(-3 * 72, 3 * 72, 72), linetype = 2, size = .5, alpha = .5 )
    

    如果不需要文本标签和虚线,请省略最后两行。

    【讨论】: