geom_boxplot() from ggplot2 : forcing an empty level to appear

前端 未结 1 1850
后悔当初
后悔当初 2020-12-09 19:42

I can\'t find a way to ask ggplot2 to show an empty level in a boxplot without imputing my dataframe with actual missing values. Here is reproducible code :

         


        
相关标签:
1条回答
  • 2020-12-09 20:41

    You can control the breaks in a suitable scale function, in this case scale_x_discrete. Make sure you use the argument drop=FALSE:

    p <- ggplot(data=dftest[dftest$time!=2,],aes(x=factor(time,levels=1:10),y=value))
    p + geom_boxplot() + 
      scale_x_discrete("time", breaks=factor(1:10), drop=FALSE)
    

    enter image description here


    I like to do my data manipulation in advance of sending it to ggplot. I think this makes the code more readable. This is how I would do it myself, but the results are the same. Note, however, that the ggplot scale gets much simpler, since you don't have to specify the breaks:

    dfplot <- dftest[dftest$time!=2, ]
    dfplot$time <- factor(dfplot$time, levels=1:10)
    
    ggplot(data=dfplot, aes(x=time ,y=value)) +
        geom_boxplot() + 
        scale_x_discrete("time", drop=FALSE)
    
    0 讨论(0)
提交回复
热议问题