0

In the following example, ggplots ignores my order when stacking the bars of the barplot. Note that the order is respected in the legend.

  1. prepeare the data:

    plotdf <-
      structure(list(.id = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
      2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 
      5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("C A", "C W", "C R", 
      "I N D", "I e", "I o"), class = "factor"), grp = structure(c(3L, 
      1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L, 
      4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L), .Label = c("C L", 
      "F C", "C", "B", "R"), class = "factor"), v = c(0, 0.239181693913566, 
      0.165857056803677, 0.350750434828833, 0.244210814453923, 0, 0.271188523388472, 
      0.0962040631815689, 0.272432818496037, 0.360174594933923, 0.0369015572477178, 
      0.29722089026182, 0.125321399722723, 0.195349629447893, 0.345206523319846, 
      0, 0.194564544482903, 0.30578720507121, 0.139178183673556, 0.360470066772331, 
      0.0263516505214496, 0.247452946164384, 0.400260126370759, 0.0579795532895398, 
      0.267955723653867, 0, 0.369045931493036, 0.372811575779409, 0, 
      0.258142492727555)), .Names = c(".id", "grp", "v"), row.names = c(NA, 
      -30L), class = "data.frame")
    
  2. look at the data -- there are factors

    head(plotdf)
    ##   .id grp         v
    ## 1 C A   C 0.0000000
    ## 2 C A C L 0.2391817
    ## 3 C A   B 0.1658571
    ## 4 C A F C 0.3507504
    ## 5 C A   R 0.2442108
    ## 6 C W   C 0.0000000
    
    str(plotdf)
    ## 'data.frame':    30 obs. of  3 variables:
    ##  $ .id: Factor w/ 6 levels "C A","C W","C R",..: 1 1 1 1 1 2 2 2 2 2 ...
    ##  $ grp: Factor w/ 5 levels "C L","F C","C",..: 3 1 4 2 5 3 1 4 2 5 ...
    ##  $ v  : num  0 0.239 0.166 0.351 0.244 ...
    
    head(plotdf$grp)
    ## [1] C   C L B   F C R   C  
    ## Levels: C L F C C B R
    
  3. plot

    ggplot(plotdf, aes(x=.id, y=v, fill=grp)) + geom_bar(stat="identity")
    

    gives me resulting plot

Andreas
  • 1,106
  • 9
  • 26

1 Answers1

2

The order of the factor levels specifies the order of values along the axis and in the legend. But for what ever reason, when you are stacking barplots, you must also set the order= aesthetic. Use

ggplot(plotdf, aes(x=.id, y=v, fill=grp, order=grp)) + geom_bar(stat="identity")

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks a lot. Works like a charm. I for sure got some gray hair over this one. I will remember that. Just out of curiosity: Is that documented somewhere? Do you know? – Andreas Aug 28 '14 at 14:23
  • Honestly I'm not sure where it's documented. I just know because someone asked a similar question somewhat recently ;) – MrFlick Aug 28 '14 at 14:33