4

我有一个给出平均值和 SD 的数据:

#info mean sd
info1 20.84 4.56
info2 29.18 5.41
info3 38.90 6.22

实际上有100多行。给定上述数据,如何绘制一张图中每一行的正态分布?

4

2 回答 2

8

根据 N 真正得到的大小,您可能希望将其拆分为一组多个图表。但是,这是基本方法。首先,您需要根据您的均值和标准差生成一些随机数据。我选择了1000个随机点,你可以根据需要调整。接下来,设置一个具有适当尺寸的空白图,然后使用linesdensity添加数据。我使用了 for 循环,因为它提供了一种为每个数据点指定线型的好方法。最后,在最后添加一个图例:

dat <- read.table(text = "info mean sd
info1 20.84 4.56
info2 29.18 5.41
info3 38.90 6.22
", header = TRUE)

densities <- apply(dat[, -1], 1, function(x) rnorm(n = 1000, mean = x[1], sd = x[2]))
colnames(densities) <- dat$info

plot(0, type = "n", xlim = c(min(densities), max(densities)), ylim = c(0, .2))
for (d in 1:ncol(densities)){
  lines(density(densities[, d]), lty = d)
}
legend("topright", legend=colnames(densities), lty=1:ncol(densities))

在此处输入图像描述

或者,使用 ggplot2 可以带来很多好处,即它会自动为您指定合理的 xlim 和 ylim 值,并用图例做明智的事情而不会大惊小怪。

library(reshape2)
library(ggplot2)
#Put into long format
densities.m <- melt(densities)
#Plot
ggplot(densities.m, aes(value, linetype = Var2)) + geom_density()

在此处输入图像描述

于 2012-04-27T02:01:07.223 回答
6

又是一美元的空头和一天的迟到。蔡斯的反应非常彻底。这是我的破解:

dat <- read.table(text="info  mean  sd
info1 20.84 4.56
info2 29.18 5.41
info3 38.90 6.22", header=T)

dat <- transform(dat, lower= mean-3*sd, upper= mean+3*sd)

plot(x=c(min(dat$lower)-2, max(dat$upper)+2), y=c(0, .25), ylab="", 
    xlim=c(min(dat$lower)-2, max(dat$upper)+2), xlab="", 
    axes=FALSE, xaxs = "i", type="n")
box()

FUN <- function(rownum) {
    par(new=TRUE)
    curve(dnorm(x,dat[rownum, 2], dat[rownum, 3]),
        xlim=c(c(min(dat$lower)-2, max(dat$upper)+2)), 
        ylim=c(0, .22),
        ylab="", xlab="")
}

lapply(seq_len(nrow(dat)), function(i) FUN(i))

在此处输入图像描述

于 2012-04-27T02:11:25.177 回答