R- split histogram according to factor level

后端 未结 2 1509
野趣味
野趣味 2020-12-02 21:00

This is my data:

type<-rep(c(0,1),100) 
diff<-rnorm(100)
data<-data.frame(type,diff)

If I want to plot historgram of diff

2条回答
  •  长情又很酷
    2020-12-02 21:41

    You can use the ggplot2 package:

    library(ggplot2)
    
    ggplot(data,aes(x=diff))+geom_histogram()+facet_grid(~type)+theme_bw()
    

    You can also put them on the same plot by "dodging" them:

    ggplot(data,aes(x=diff,group=type,fill=type))+
      geom_histogram(position="dodge",binwidth=0.25)+theme_bw()
    

    If you want them to overlap, the position has to be position="identity"

    ggplot(data,aes(x=diff,group=type,fill=type))+
      geom_histogram(position="identity",alpha=0.5,binwidth=0.25)+theme_bw()
    

    If you want them to look like it does in the first one but without the border, you have to hack it a little:

    data$diff[data$type==1] <- data$diff[data$type==1] + 6
    
    ggplot(data,aes(x=diff,group=type,fill=type))+
      geom_histogram(position="identity",alpha=0.5,binwidth=0.25)+theme_bw()+
      scale_x_continuous(breaks=c(-2:2,4:8),labels=c(-2:2,-2:2))
    

提交回复
热议问题