Adding Shaded region to histogram between quintiles

后端 未结 1 716
醉酒成梦
醉酒成梦 2021-01-23 15:02

All,

I have a chart that has 2 histograms in which I also plotted lines representing the 20th, 40th, 60th and 80th percentiles, the code below reproduces a similar chart

相关标签:
1条回答
  • 2021-01-23 15:38

    After more experimentation, I was able to solve it using the following code

    What was tricking geom_rect somehow was that it wanted an x variable (so I renamed q40 on q). I am not sure why ggplot does not like xmin=q40, but it likes xmax=q60

    data <- rbind(data.frame(x=rnorm(1000,0,1),g="one"),data.frame(x=rnorm(1000,0.2,1.5),g="two"))
    q = ddply(melt(data,id.vars="g"),.(g),summarise,q20=quantile(value,.2,na.rm=T),
              q40=quantile(value,.4,na.rm=T),q60=quantile(value,.6,na.rm=T),q80=quantile(value,.8,na.rm=T))
    q1 = melt(q)
    names(q)[3] = 'x'
    
    ch <- ggplot(data,aes(x=x,fill=g))+
      geom_vline(data=q1,aes(xintercept=value,group=variable),linetype=2,color="black")+
      geom_histogram(aes(y=..density..),alpha=0.75,binwidth=0.1)+facet_grid(g~.)+theme_bw()+coord_cartesian(xlim=c(-3,3))+
      coord_cartesian(ylim=c(0,0.5))++geom_rect(data=q,aes(xmin=x,xmax=x1,ymin=0,ymax=.5,group=g),fill="gray",alpha=0.1)
    ch
    

    enter image description here

    0 讨论(0)
提交回复
热议问题