问题描述
hist(www,prob=TRUE,xlab = "X",main = "Plot",xlim=c(0,11),ylim=c(0,1),breaks =100)
lines(density(x,adjust=5),col="red",lwd=2)
lines(density(y,col="blue",lwd=2)
lines(density(z,col="green",lwd=2)
结果如图所示。 如何删除直方图?先感谢您!
解决方法
使用三个玩具向量,试试这个:
x <- rnorm(100,1)
y <- rnorm(100,0.5,2)
z <- rnorm(100,1,1)
plot(density(x,adjust = 5),col = "red",lwd = 2,xlim = c(-20,20),ylim = c(0,0.25),xlab = "X")
par(new=T)
plot(density(y,col = "blue",xlab = "")
par(new=T)
plot(density(z,col = "green",xlab = "")
您需要以正确的方式调整 xlim
和 ylim
您可以使用 plot(density(...))
代替 hist
:
set.seed(123)
x <- rnorm(100,1)
dens <- lapply(list(x=x,y=y,z=z),density)
ran <- apply(do.call(rbind,sapply(dens,function(i) list(data.frame(x=range(i$x),y=range(i$y))))),2,range)
plot(dens[[1]],xlim=ran[,1],ylim=ran[,2],type = 'n',main="Density")
lapply(seq_along(dens),function(i) lines(dens[[i]],col=i))
legend("topright",names(dens),col=seq_along(dens),lty=1)
由 reprex package (v1.0.0) 于 2021 年 1 月 31 日创建
使用 ggplot2
包更容易绘图:
library(ggplot2)
dat <-data.frame(group=unlist(lapply(c("x","y","z"),function(i) rep(i,length(get(i))))),value=c(x,y,z))
ggplot(dat,aes(x=value,colour=group))+
geom_density()