R 中具有正态曲线和误差条的直方图

Histogram with normal curve and error bars in R


    #import data
    data = diameters$V1
    error = .005 #mm

    #make histogram
    h <- hist(data, breaks = "FD", density = 10,
              col = "lightblue", xlab = "Diameter", main = "Overall") 

    # Make normal curve
    xfit <- seq(min(data), max(data), length = 40) 
    yfit <- dnorm(xfit, mean = mean(data), sd = sd(data)) 
    yfit <- yfit * diff(h$mids[1:2]) * length(data) 

    #Draw normal curve
    lines(xfit, yfit, col = "black", lwd = 2)

输出:

期望:

是否可以在没有任何外部库的情况下使用 +/- 误差值将误差条添加到直方图?

您应该可以使用 arrows() 函数绘制它们:

## Create a histogram from random data
> hist(sample(runif(100)))
> arrows(x0 = 0.15, y0 = 11, x1 = 0.15, y1 = 13, code = 3, length = 0.05, angle = 90)

x0x1 指定开始和结束 x 坐标(对于垂直直线,保持相同)

y0y1 指定开始和结束 y 坐标,例如要绘制的线的长度。

code = 3 告诉 R 绘制双面 'arrow',angle = 90 使 'arrow' 成为一条平线,length = 0.05 指定误差线的宽度应该是。

有关详细信息,请参阅 ?arrows