Different breaks per facet in ggplot2 histogram

前端 未结 4 1648
青春惊慌失措
青春惊慌失措 2020-11-30 07:40

A ggplot2-challenged latticist needs help: What\'s the syntax to request variable per-facet breaks in a histogram?

library(ggplot2)
d = data.frame(x=c(rnorm(         


        
4条回答
  •  猫巷女王i
    2020-11-30 08:22

    Following on from Didzis example:

    ggplot(dat=d, aes(x=x, y=..ncount..)) +
      geom_histogram(data = d[d$par == "a",], binwidth=0.1) +
      geom_histogram(data = d[d$par == "b",], binwidth=0.01) +  
      facet_grid(.~ par, scales="free")
    

    EDIT: This works for more levels but of course there are already better solutions

    # More facets
    d <- data.frame(x=c(rnorm(200,10,0.1),rnorm(200,20,0.1)),par=rep(letters[1:4],each=100))
    
    # vector of binwidths same length as number of facets - need a nicer way to calculate these
    my.width=c(0.5,0.25,0.1,0.01)
    
    out<-lapply(1:length(my.width),function(.i) data.frame(par=levels(d$par)[.i],ggplot2:::bin(d$x[d$par==levels(d$par)[.i]],binwidth=my.width[.i])))
    
    my.df<-do.call(rbind , out)
    
    ggplot(my.df) + geom_histogram(aes(x, y = density, width = width), stat =  "identity") + facet_wrap(~par,scales="free")
    

    from https://groups.google.com/forum/?fromgroups=#!searchin/ggplot2/bin$20histogram$20by$20facet/ggplot2/xlqRIFPP-zE/CgfigIkgAAkJ

提交回复
热议问题