【问题标题】:Plot density lines without histogram绘制没有直方图的密度线
【发布时间】:2021-05-04 23:10:33
【问题描述】:

我想在不显示直方图的情况下绘制密度线,我使用了以下代码:

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)

结果显示在图片中。 如何删除直方图?先感谢您!

【问题讨论】:

    标签: r plot histogram density-plot


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      您可以使用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()
      

      【讨论】:

        猜你喜欢
        • 2014-08-20
        • 1970-01-01
        • 2015-02-23
        • 1970-01-01
        • 2014-04-10
        • 1970-01-01
        • 2017-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多