ggplot: arranging boxplots of multiple y-variables for each group of a continuous x

后端 未结 1 844
走了就别回头了
走了就别回头了 2020-12-08 01:35

I would like to create boxplots of multiple variables for groups of a continuous x-variable. The boxplots should be arranged next to each other for each group of x.

相关标签:
1条回答
  • 2020-12-08 02:05

    Not exactly sure what you're looking for. Is this close?

    enter image description here

    library(ggplot2)
    library(plyr)
    ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
      geom_boxplot()+
      facet_grid(.~variable)+
      labs(x="X (binned)")+
      theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
    

    EDIT (response to OP's comment)

    You can put the Y's next to each other in each bin by just taking out the facet_grid(...) call, but I don't recommend it.

    ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value, fill=variable))+
      geom_boxplot()+
      labs(x="X (binned)")+
      theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
    

    If you have to do it this way, it's still clearer using facets:

    dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
    ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
      geom_boxplot()+
      facet_grid(.~bin, scales="free")+
      labs(x="X (binned)")+
      theme(axis.text.x=element_blank())
    

    Note the addition of a bin column to dfmelt. This is because using factor(round_any(x,0.5)) in the facet_grid(...) formula doesn't work.

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