开发者

R Density Graph: How can I add a solid line from the x-axis to the top of the density curve

I have a density plot graphed using:

plot(density(x))

What I am interested in doing is creating a line for something like x = 5 from the x-axis to the corresponding spot on the curve.

Lik开发者_JAVA百科e this:

R Density Graph: How can I add a solid line from the x-axis to the top of the density curve


You can do this by first storing the density values in an object, and then retrieving the x and y elements from this object. In the following example I use findInterval to retrieve the y-value for the given x-value:

x <- rnorm(1000) # Sample data
y <- density(x)  # Calculate and store density

x0 <- 2 # Desired position on x-axis
y0 <- y$y[findInterval(x0, y$x)] # Corresponding y value

plot(density(x))
segments(x0, 0, x0, y0)

R Density Graph: How can I add a solid line from the x-axis to the top of the density curve


If it's really z-scores then just actually plot the density function dnorm(). It also looks like you'd like to have your actual x-axis at 0.

zmax <- 4
curve(dnorm, -zmax, zmax, xaxt = 'n', bty = 'n')
axis(1, -zmax:zmax, pos = 0)

To draw in your line you can use the dnorm function again.

zscore <- 1.65
segments(zscore, 0, zscore, dnorm(zscore))

You could also even shade it out nicely... :)

x <- seq(zscore, zmax, 0.01)
y <- c(0, dnorm(x)[1:(length(x)-2)],0)
polygon(x,y, density = 20)

You can also use segments and the text command to put the labels right on your graph of what the shaded and unshaded areas mean.

R Density Graph: How can I add a solid line from the x-axis to the top of the density curve

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜