绘制没有直方图的密度线

Plot density lines without histogram

我想绘制密度线而不显示直方图,我使用了这段代码:

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, adjust=5), col="blue", lwd=2) 
lines(density(z, adjust=5), col="green", lwd=2)

结果如图所示。 如何删除直方图?先感谢您!

使用三个玩具矢量,试试这个:

x <- rnorm(100, 0, 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, adjust = 5), col = "blue", lwd = 2, 
     xlim = c(-20, 20), ylim = c(0, 0.25), xlab = "") 
par(new=T)
plot(density(z, adjust = 5), col = "green", lwd = 2, 
     xlim = c(-20, 20), ylim = c(0, 0.25), xlab = "")

您需要以正确的方式调整 xlimylim

您可以使用 plot(density(...)) 而不是 hist:

set.seed(123)
x <- rnorm(100, 0, 1)
y <- rnorm(100, 0.5, 2)
z <- rnorm(100, 1, 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-01-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()