R语言 在图的X轴上标记平均值

cld4siwp  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(167)

我想让均值显示在X轴上,但我只能让它显示在X轴的上方:

curve(dnorm(x, mean=mu, sd=s), from=0, to=80, xlab="Horas", ylab="f(x)")
abline(v=mu, col='red', lty=3)
abline(v=mu - s/2, col='blue', lty=3)
abline(v=mu + s/2, col='blue', lty=3)
legend("topright", legend=c("", ""), 
       title=(paste("N(", mu, ", ", s, ")")), 
       title.adj=0, lty=0, lwd=0, box.lty=0)
text(mu, 0, labels=mu)
box()
tyu7yeag

tyu7yeag1#

使用mtext()代替text()(代表 margin text):

mu <- 41; s <- 5

curve(dnorm(x, mean=mu, sd=s), from = 0, to = 80, xlab="Horas", ylab="f(x)")
abline(v=mu, col='red', lty=3)
abline(v=mu-(s/2), col='blue', lty=3)
abline(v=mu+(s/2), col='blue', lty=3)
legend("topright", legend = c("", ""), 
       title = (paste("N(",mu,",",s,")")),
       title.adj = 0, lty = 0, lwd = 0, box.lty = 0 )
mtext(mu, 1, at=mu)
box()

您可以使用line =参数调整文本的y位置。阅读help(mtext)
如果你不想在边界处添加均值,而是想在x轴上添加均值,你必须首先通过添加xaxt='n'参数来禁止在curve()中绘制原始x轴,然后用axis(1)手动绘制轴。
示例:

mu <- 41; s <- 5

curve(dnorm(x, mean=mu, sd=s), from = 0, to = 80, xlab="Horas", ylab="f(x)", xaxt="n")
abline(v=mu, col='red', lty=3)
abline(v=mu-(s/2), col='blue', lty=3)
abline(v=mu+(s/2), col='blue', lty=3)
legend("topright", legend = c("", ""), 
       title = (paste("N(",mu,",",s,")")),
       title.adj = 0, lty = 0, lwd = 0, box.lty = 0 )
axis(1, at = c(0,20,41,60,80))
box()

hiz5n14c

hiz5n14c2#

我们可以让它更动态,例如从0到大约2乘以mu的曲线。如果我们在x轴上有通常的四舍五入间距,突出显示平均值,它可能看起来更好,显然max(pretty(mu*2/3))工作得不太糟糕。最后,abline s可以一步绘制,bquote有助于用方程进行动态表达。

x0 <- 0; x1 <- 2*mu

curve(dnorm(x, mean=mu, sd=s), from=x0, to=x1, xlab="Horas", ylab='', xaxt='n')
## y-lab
mtext(bquote(italic(f)~(x)), 2, 2.5)
## lines
abline(v=mu + s*c(0, 1/2, -1/2), col=c('red', 'blue', 'blue'), lty=3)
## normal x-axis
axis(1, seq(x0, x1, max(pretty(mu*2/3))))
## mu on x-axis
axis(1, mu, labels=FALSE, col='red')  
mtext(mu, side=1, line=1, at=mu, col='red')
## legend
legend('topright', legend=bquote(N(.(mu), .(s))), bty='n')

  • 数据:*
set.seed(42)  ## some random mu and sd
mu <- trunc(runif(1)*100); s <- trunc(runif(1)*10)

相关问题