Include space for missing factor level used in fill aesthetics in geom_boxplot

后端 未结 2 656
感情败类
感情败类 2020-11-29 06:37

I am trying to draw a box and whisker plot in R. My code is below. At the moment, because I only have data for two months in one of the two sites, the bars are wider for tha

2条回答
  •  遥遥无期
    2020-11-29 07:12

    Here is a solution, which is based on creating fake data:

    Firstly, a new row is added to the data frame. It contains a data point for the non-existing combination of factor levels (Mar and A). The value of Height has to be outside the range of the real Height data.

    Data2 <- rbind(Data, data.frame(Month = "Mar", Site = "A", Height = 5))
    

    Then, the plot can be generated. Since the fake data should not be visible, the y axis limits have to be modified with coord_cartesian and the range of the original Height data.

    library(ggplot2)
    ggplot(Data2, aes(Site, Height)) +
      geom_boxplot(aes(fill = Month)) +
      coord_cartesian(ylim = range(Data$Height) + c(-.25, .25))
    

    enter image description here

提交回复
热议问题