0
votes

I want to plot density lines without showing the histogram, I used this code:

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)

And the result is showing in the the picture. How can I remove the Histogram? Thank you in advance! enter image description here

2

2 Answers

0
votes

Using three toy vectors, try this:

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 = "")

You will need to adjust xlim and ylim in the right way

0
votes

You could use plot(density(...)) instead of 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)

Created on 2021-01-31 by the reprex package (v1.0.0)

Even easier is plotting with the ggplot2 package:

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()