为均值添加线以绘制

Add line for mean to plot

我想在我的图中添加一条线来指示平均值:

X1 <- rnorm(100)
# Kernel density estimates
density_X1 <- density(X1)
# Compute mode
mode_X1 <- density_X1$x[which.max(density_X1$y)]; mode_X1
# Compute mean
mean_X1 <- mean(X1)
# Create plot 
plot(density_X1, main = "Kernel density estimates", xlab = "X1", ylab = "density")
# Add line for mode
segments(x0 = mode_X1, y0 = 0, x1 = mode_X1, y1 = density_X1$y, col = "red", lty = 1, lwd = 1)
# Add line for mean
segments(x0 = mean_X1, y0 = 0, x1 = mean_X1, y1 = , col = "red", lty = 5, lwd = 2)

我需要为 segments(y1 = ) 输入什么值才能确保上限是核密度图?

您也可以这样使用 abline

X1 <- rnorm(100)
# Kernel density estimates
density_X1 <- density(X1)
# Compute mode
mode_X1 <- density_X1$x[which.max(density_X1$y)]; mode_X1
# Compute mean
mean_X1 <- mean(X1)
# Create plot 
plot(density_X1, main = "Kernel density estimates", xlab = "X1", ylab = "density")
abline(v = mode_X1, col = "red", lty = 1, lwd = 1)
abline(v = mean_X1, col = "red", lty = 5, lwd = 2)

输出:

要根据离散点处的密度估计计算某些 x-value 处的 y-value,您需要进行某种插值。一种方法是使用 approx:

的线性插值
approx(x = density_X1$x, y = density_X1$y, xout = mean_X1)$y

其中,xy 给出要插值的点,xout x-value 的(矢量)插值完成的位置(参见 ?approx)

所以代码是:

set.seed(72405277)
X1 <- rnorm(100)
# Kernel density estimates
density_X1 <- density(X1)
# Compute mode
mdIdx <- which.max(density_X1$y) # store and resuse
mode_X1 <- density_X1$x[mdIdx]; 
# Compute mean
mean_X1 <- mean(X1)
# Create plot 
plot(density_X1, main = "Kernel density estimates", xlab = "X1", ylab = "density")
# Add line for mode
segments(x0 = mode_X1, y0 = 0, x1 = mode_X1, y1 = density_X1$y[mdIdx], col = "red", lty = 1, lwd = 1)
# Add line for mean
yax2 <- approx(x = density_X1$x, y = density_X1$y, xout = mean_X1)$y
segments(x0 = mean_X1, y0 = 0, x1 = mean_X1, y1 = yax2, col = "blue", lty = 5, lwd = 2)