How to change order of boxplots when using ggplot2?

前端 未结 2 1321
终归单人心
终归单人心 2020-12-03 01:27

This question follows from this other one. I was unable to implement answers there.

Define:

df2 <- data.frame(variable=rep(c(\"vnu.shr\",\"vph.sh         


        
相关标签:
2条回答
  • 2020-12-03 01:52

    You've already accepted a (perfectly fine) solution, but here's another option using relevel(). I'm not sure why it wasn't working for you?

    #default plot
    ggplot(df2, aes(variable, value)) + geom_boxplot()
    

    enter image description here

    #Reverse reverse!
    df2$variable2 <- with(df2, relevel(variable, "vph.shr"))
    ggplot(df2, aes(variable2, value)) + geom_boxplot()
    

    enter image description here

    0 讨论(0)
  • 2020-12-03 01:55

    Have you tried this:

    df2$variable <- factor(df2$variable,
        levels = c('vph.shr','vnu.shr'),ordered = TRUE)
    

    I just picked an ordering there, since my system is configured slightly differently than yours I suspect, so my 'default ordering' may differ. But you can just switch the position of levels when specifying them.

    A few other options, depend on your tastes:

    For just reversing the current ordering:

    factor(df2$variable,levels = rev(levels(df2$variable)),ordered = TRUE)
    

    or you can use subsetting to specify a specific ordering if you don't want to type out each level by hand:

    factor(df2$variable,levels = levels(df2$variable)[1:2],ordered = TRUE)
    
    0 讨论(0)
提交回复
热议问题