Order of legend entries in ggplot2 barplots with coord_flip()

前端 未结 1 994
一个人的身影
一个人的身影 2020-12-09 05:14

I\'m struggling get the right ordering of variables in a graph I made with ggplot2 in R.

Suppose I have a dataframe such as:

set.seed(1234)
my_df<         


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

    This has little to do with ggplot, but is instead a question about generating an ordering of variables to use to reorder the levels of a factor. Here is your data, implemented using the various functions to better effect:

    set.seed(1234)
    df2 <- data.frame(year = rep(2006:2007), 
                      variable = rep(c("VX","VB","VZ","VD"), each = 2),
                      value = runif(8, 5,10),
                      vartype = rep(c("TA","TB"), each = 4))
    

    Note that this way variable and vartype are factors. If they aren't factors, ggplot() will coerce them and then you get left with alphabetical ordering. I have said this before and will no doubt say it again; get your data into the correct format first before you start plotting / doing data analysis.

    You want the following ordering:

    > with(df2, order(vartype, variable))
    [1] 3 4 1 2 7 8 5 6
    

    where you should note that we get the ordering by vartype first and only then by variable within the levels of vartype. If we use this to reorder the levels of variable we get:

    > with(df2, reorder(variable, order(vartype, variable)))
    [1] VX VX VB VB VZ VZ VD VD
    attr(,"scores")
     VB  VD  VX  VZ 
    1.5 5.5 3.5 7.5 
    Levels: VB VX VD VZ
    

    (ignore the attr(,"scores") bit and focus on the Levels). This has the right ordering, but ggplot() will draw them bottom to top and you wanted top to bottom. I'm not sufficiently familiar with ggplot() to know if this can be controlled, so we will also need to reverse the ordering using decreasing = TRUE in the call to order().

    Putting this all together we have:

    ## reorder `variable` on `variable` within `vartype`
    df3 <- transform(df2, variable = reorder(variable, order(vartype, variable,
                                                             decreasing = TRUE)))
    

    Which when used with your plotting code:

    ggplot(df3, aes(x=variable, y=value, fill=vartype)) +
           geom_bar() + 
           facet_grid(. ~ year) + 
           coord_flip()
    

    produces this:

    reordered barplot

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