我有两个数字向量,我想为每个向量绘制直方图+正常曲线。
第一个数字向量:
dput(X)
structure(c(18.9006028896526, 15.2623176606927, 23.9827366796017,
18.6674504871855, 33.8321828287622, 106.070218436199, 33.7827125058274,
138.544803100033, 98.8988553851087, 84.6705010348182, 90.0070387381623,
97.842536232733, 6.75830201534835, 24.105734944894, 18.9289005033733,
107.837417018034, 91.2295363960887, 120.394907406909, 23.4284311509232,
27.936658956423), .Names = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"))
第二个数字向量:
> dput(Y)
structure(c(4.98024718191362, 4.97784623179944, 37.54860832645,
34.0616843614727, 146.39674720645, 17.3962674768585, 40.896642118419,
71.7799735926384, 46.5749573881639, 39.3924128572005, 137.396714992547,
111.856816465825, 80.8041773807388, 24.1694521970975, 15.700639434151
), .Names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"))
这些载体的长度不同。我想应用类似下面的代码,我用于单个直方图和估计正常曲线:
h<-hist(X, breaks=25, col="green", xlab="Graph",
main="Histogram and Normal Curve", xlim = c(0, 100))
xfit<-seq(min(X),max(X),length=40)
yfit<-dnorm(xfit,mean=mean(X),sd=sd(X))
yfit <- yfit*diff(h$mids[1:2])*length(X)
lines(xfit, yfit, col="blue", lwd=2)
期望的输出:
答案 0 :(得分:2)
如果您希望两个直方图并排显示,可以使用par()
功能:
hist(X, breaks=25, col=rgb(0,1,0,alpha=.25), xlab="Graph",
main="Histograms and Normal Curves", xlim = c(0, 100))
xfit<-seq(min(X),max(X),length=40)
yfit<-dnorm(xfit,mean=mean(X),sd=sd(X))
yfit <- yfit*diff(h$mids[1:2])*length(X)
lines(xfit, yfit, col="green", lwd=2)
hist(Y, breaks=25, col=rgb(1,0,0, alpha=0.25), xlim = c(0, 100), add=TRUE)
xfit2<-seq(min(Y),max(Y),length=40)
yfit2<-dnorm(xfit2,mean=mean(Y),sd=sd(Y))
yfit2 <- yfit2*diff(h$mids[1:2])*length(Y)
lines(xfit2, yfit2, col="red", lwd=2)
最后的情节:
这里的关键是使用alpha
函数的rgb()
参数使条形变为半透明。您可以在this link