【问题标题】:multiple histograms on top of eachother without bins多个直方图相互叠加,没有 bin
【发布时间】:2011-05-17 13:50:21
【问题描述】:

假设我有这个有 2 个级别的数据框。 LC和HC。 现在我想在彼此之上获得 2 个如下图。

data <- data.frame(
    welltype=c("LC","LC","LC","LC","LC","HC","HC","HC","HC","HC"),
    value=c(1,2,1,2,1,5,4,5,4,5))

获取以下情节的代码=

x <- rnorm(1000)
y <- hist(x)
plot(y$breaks,
   c(y$counts,0),
   type="s",col="blue")

(感谢 Joris Meys)

那么,我该如何开始呢。由于我习惯了 java,所以我正在考虑一个 for 循环,但有人告诉我不要这样做。

【问题讨论】:

    标签: r plot histogram


    【解决方案1】:

    除了 Aaron 提供的方法之外,还有一个 ggplot 解决方案(见下文), 但我强烈建议您使用密度,因为它们会提供更好的图并且更容易构建:

    # make data
    wells <- c("LC","HC","BC")
    Data <- data.frame(
        welltype=rep(wells,each=100),
        value=c(rnorm(100),rnorm(100,2),rnorm(100,3))
    )
    
    ggplot(Data,aes(value,fill=welltype)) + geom_density(alpha=0.2)
    

    给 :

    对于您要求的情节:

    # make hists dataframe
    hists <- tapply(Data$value,Data$welltype,
                function(i){
                  tmp <- hist(i)
                  data.frame(br=tmp$breaks,co=c(tmp$counts,0))
                })
    ll <- sapply(hists,nrow)
    hists <- do.call(rbind,hists)
    hists$fac <- rep(wells,ll)
    
    # make plot
    require(ggplot2)
    qplot(br,co,data=hists,geom="step",colour=fac)
    

    【讨论】:

      【解决方案2】:

      您可以使用相同的代码,除了点而不是绘图来向绘图添加额外的线。

      编造一些数据

      set.seed(5)
      d <- data.frame(x=c(rnorm(1000)+3, rnorm(1000)),
                      g=rep(1:2, each=1000) )
      

      并以相当简单的方式进行:

      x1 <- d$x[d$g==1]
      x2 <- d$x[d$g==2]
      y1 <- hist(x1, plot=FALSE)
      y2 <- hist(x2, plot=FALSE)
      plot(y1$breaks, c(y1$counts,0), type="s",col="blue",
           xlim=range(c(y1$breaks, y2$breaks)), ylim=range(c(0,y1$counts, y2$counts)))
      points(y2$breaks, c(y2$counts,0), type="s", col="red")
      

      或者以更 R-ish 的方式:

      col <- c("blue", "red")
      ds <- split(d$x, d$g)
      hs <- lapply(ds, hist, plot=FALSE)
      plot(0,0,type="n",
           ylim=range(c(0,unlist(lapply(hs, function(x) x$counts)))),
           xlim=range(unlist(lapply(hs, function(x) x$breaks))) )
      for(i in seq_along(hs)) {
        points(hs[[i]]$breaks, c(hs[[i]]$counts,0), type="s", col=col[i])
      }
      

      编辑:受 Joris 回答的启发,我注意到 lattice 也可以轻松绘制重叠密度图。

      library(lattice)
      densityplot(~x, group=g, data=d)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-17
        • 2016-12-30
        • 2016-02-07
        • 1970-01-01
        • 2011-06-16
        • 2021-05-11
        • 1970-01-01
        相关资源
        最近更新 更多