title: Ordering Legend in Multi-Bar ggplot2 Chart
body: <p>I would like to have a multi-bar chart, horizontal bars, where the legend for the bar-color is in the same order as the bars themselves.  I've looked at several articles that have influenced the example here, but I can't make it work.</p>
  
  <p>In this example, it is the "Group" that is in one order in the bars, and the reverse order in the legend.</p>
  
  <pre><code>library(ggplot2)
  
  # create data for tidy format
  Category &lt;- c("Category1","Category2","Category3","Category4","Category5","Category1","Category2","Category3","Category4","Category5","Category1","Category2","Category3","Category4","Category5")
  GroupTitle &lt;- c("GroupA","GroupA","GroupA","GroupA","GroupA","GroupB","GroupB","GroupB","GroupB","GroupB","GroupC","GroupC","GroupC","GroupC","GroupC")
  Valuelst &lt;- list()
  for (i in 1:15){
    Valuelst[i] &lt;- runif(1, min=0, max=1)
  }
  Valuelst &lt;- unlist(Valuelst)
  # make data frame
  d &lt;- data.frame(Category,GroupTitle,Valuelst)
  
  # set factors and orders desired
  d$Category &lt;- factor(d$Category, levels = c("Category5","Category4","Category3","Category2","Category1"))
  d$GroupTitle &lt;- factor(d$GroupTitle, levels = c("GroupA","GroupB","GroupC"))
  
  # make graph
  ggplot(d, aes(x=Category, y=Valuelst, order = -as.numeric(GroupTitle))) + # order= -as.numeric() is one solution that I read
    geom_bar(aes(fill=GroupTitle), stat="identity", position="dodge") + 
    coord_flip() +
    scale_fill_manual("Legenda", values = c("GroupC" = "#deebf7", "GroupB" = "#3182bd", "GroupA" = "#9ecae1")) # scale_fill_manual is another I read
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/kgVZ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kgVZ4.png" alt="Output of the code"></a></p>
  
  <p>I've commented in the code a couple of places where I tried solutions I saw elsewhere. Namely, I've made sure the Groups are a factor, set the order of that factor, used <code>order = -as.numeric(GroupTitle)</code>, and tried <code>scale_fill_manual</code>, all with no effect.</p>