0

how to order bars according to the sales within each category require(ggplot2) require(dplyr)

df <- data.frame (Origin = c("Canada", "Canada","USA","USA"),
                  Category = c("A", "B","A","B"),
                  Sales = c(103, 192, 144, 110))

ggplot(df, aes(fill=Category, y=Sales, x=Origin)) + 
    geom_bar(position="dodge", stat="identity") + coord_flip()
  • 1
    This was closed as a duplicate, but I voted to reopen, since the linked duplicate only dealt with rearranging bars on the x axis, not rearranging the order of dodged bars. – Allan Cameron Aug 21 '22 at 12:56

1 Answers1

2

There are a couple of ways to do this. Perhaps the simplest is to use position_dodge2(reverse = TRUE)

Note also that you are using a couple of outdated idioms. geom_bar(stat = "identity") is just a long way of writing geom_col, and you don't need to use coord_flip, since ggplot will know that you intended a horizontal bar plot if you just reverse the x and y aesthetics.

ggplot(df, aes(fill = Category, x = Sales, y = Origin)) + 
  geom_col(position = position_dodge2(reverse = TRUE))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • 2
    @user4567794374545 can you edit your question to show an example of when the default ordering is correct? Thanks. – Allan Cameron Aug 21 '22 at 11:28
  • 1
    @user4567794374545 OK. It would be great if you could edit your question to show an example where the ordering of the bars is the right way round and reverse = TRUE won't work for you. It's going to be difficult to help you without seeing an example of this. – Allan Cameron Aug 21 '22 at 14:47
  • @user4567794374545 but that is exactly the line that needs to be fixed to give you the correct result. Can you explain why you need to keep that line? There are other solutions, but they make it more complex than it needs to be. – Allan Cameron Aug 21 '22 at 16:46
  • How about https://stackoverflow.com/questions/16528065/how-to-order-subgroups-in-a-ggplot-barplot or https://stackoverflow.com/questions/1721536/changing-the-order-of-dodged-bars-in-ggplot2-barplot or https://stackoverflow.com/questions/23245294/ggplot2-ordering-dodged-columns. there are so many duplicates to this type of question! – tjebo Aug 21 '22 at 17:34
  • 2
    @tjebo I'm not sure any of these are quite what the OP was looking for (I thought it might be a more subtle question, hence why I was asking for clarification). Anyway, in the absence of a clear explanation of why my answer or any of the duplicates don't work, I think your use of the dupe hammer is right here. – Allan Cameron Aug 21 '22 at 17:44