Stacked histograms like in flow cytometry

前端 未结 5 1201
攒了一身酷
攒了一身酷 2020-12-15 14:45

I\'m trying to use ggplot or base R to produce something like the following:

\"enter

5条回答
  •  醉梦人生
    2020-12-15 15:14

    I think it's going to be difficult to get ggplot to offset the histograms like that. At least with faceting it makes new panels, and really, this transformation makes the y-axis meaningless. (The value is in the comparison from row to row). Here's one attempt at using base graphics to try to accomplish a similar thing.

    #plotting function
    plotoffsethists <- function(vals, groups, freq=F, overlap=.25, alpha=.75, colors=apply(floor(rbind(col2rgb(scales:::hue_pal(h = c(0, 360) + 15, c = 100, l = 65)(nlevels(groups))),alpha=alpha*255)),2,function(x) {paste0("#",paste(sprintf("%02X",x),collapse=""))}), ...) {
        print(colors)
        if (!is.factor(groups)) {
            groups<-factor(groups)
        }
        offsethist <- function (x, col = NULL, offset=0, freq=F, ...) {
            y <- if (freq) y <- x$counts
            else 
                x$density
            nB <- length(x$breaks)
            rect(x$breaks[-nB], 0+offset, x$breaks[-1L], y+offset, col = col, ...)
        }
    
         hh<-tapply(vals, groups, hist, plot=F)
    
        ymax<-if(freq)
            sapply(hh, function(x) max(x$counts))
        else
            sapply(hh, function(x) max(x$density))
        offset<-(mean(ymax)*overlap) * (length(ymax)-1):0
        ylim<-range(c(0,ymax+offset))
        xlim<-range(sapply(hh, function(x) range(x$breaks)))
        plot.new()
        plot.window(xlim, ylim, "")
        box()
        axis(1)
    
        Map(offsethist, hh, colors, offset, freq=freq, ...)
        invisible(hh)
    }
    
    #sample call
    par(mar=c(3,1,1,1)+.1)
    plotoffsethists(my.data$V1, factor(my.data$V2), overlap=.25)
    

    plotoffsethists example

提交回复
热议问题