使用curve()函数的多个图(例如正态分布)

时间:2017-04-25 19:06:30

标签: r plot curve

我正在尝试使用curve()绘制多个函数。我的例子尝试绘制具有不同均值和相同标准差的多个正态分布。

png("d:/R/standardnormal-different-means.png",width=600,height=300)
#First normal distribution 
curve(dnorm, 
    from=-2,to=2,ylab="d(x)",
    xlim=c(-5,5))
abline(v=0,lwd=4,col="black")

#Only second normal distribution is plotted
myMean <- -1
curve(dnorm(x,mean=myMean), 
    from=myMean-2,to=myMean+2,
    ylab="d(x)",xlim=c(-5,5), col="blue")
abline(v=-1,lwd=4,col="blue")
dev.off()

由于curve()函数每次都会创建一个新图,仅绘制第二个正态分布

Plot (shows only second normal distribution)

1 个答案:

答案 0 :(得分:3)

我重新打开了这个问题,因为表面上的副本专注于绘制两个不同的函数或两个不同的y向量,并且单独调用curve。但是由于我们想要为不同的方法绘制相同的函数dnorm,我们可以自动化该过程(尽管其他问题的答案也可以以类似的方式推广和自动化)。

例如:

my_curve = function(m, col) {
  curve(dnorm(x, mean=m), from=m - 3, to=m + 3, col=col, add=TRUE)
  abline(v=m, lwd=2, col=col)
}

plot(NA, xlim=c(-10,10), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, seq(-6,6,2), rainbow(7))

enter image description here

或者,为了进一步概括,让我们允许多种方法和标准偏差,并提供关于是否包括平均线的选项:

my_curve = function(m, sd, col, meanline=TRUE) {
  curve(dnorm(x, mean=m, sd=sd), from=m - 3*sd, to=m + 3*sd, col=col, add=TRUE)
  if(meanline==TRUE) abline(v=m, lwd=2, col=col)
}

plot(NA, xlim=c(-10,10), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, rep(0,4), 4:1, rainbow(4), MoreArgs=list(meanline=FALSE))

enter image description here

您还可以使用从零开始并停在密度分布顶部的线段,而不是从图的底部一直延伸到顶部。对于正态分布,平均值也是最高密度的点。但是,我使用下面的which.max方法作为识别最大y值出现的x值的更一般方法。我还添加了线宽(lwd)和线端帽样式的参数(lend=1表示平坦而不是舍入):

my_curve = function(m, sd, col, meanline=TRUE, lwd=1, lend=1) {
  x=curve(dnorm(x, mean=m, sd=sd), from=m - 3*sd, to=m + 3*sd, col=col, add=TRUE)
  if(meanline==TRUE) segments(m, 0, m, x$y[which.max(x$y)], col=col, lwd=lwd, lend=lend)
}

plot(NA, xlim=c(-10,20), ylim=c(0,0.4), xlab="Mean", ylab="d(x)")
mapply(my_curve, seq(-5,5,5), c(1,3,5), rainbow(3))

enter image description here

相关问题