3

Using the code from here, I have realized something I do not understand:

library(ggplot2)

LoTRdata <- structure(list(Film = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 3L, 
3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("The Fellowship Of The Ring", 
"The Return Of The King", "The Two Towers"), class = "factor"), 
    Race = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 
    3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L), .Label = c("Elf", "Hobbit", 
    "Man"), class = "factor"), Gender = structure(c(1L, 2L, 1L, 
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L
    ), .Label = c("Female", "Male"), class = "factor"), Words = c(1229L, 
    971L, 14L, 3644L, 0L, 1995L, 331L, 513L, 0L, 2463L, 401L, 
    3589L, 183L, 510L, 2L, 2673L, 268L, 2459L)), .Names = c("Film", 
"Race", "Gender", "Words"), class = "data.frame", row.names = c(NA, 
-18L))

p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position = "dodge") +
  coord_flip() + guides(fill = guide_legend())

enter image description here

Why is the order of the bars reversed? And how can I change the order of the bars

I am aware that I could use guides(fill = guide_legend(reverse = TRUE)) but then the order of the bars and the legend are both reversed (the legend is not alphabetically ordered anymore).

In contrast to this question, where the order of each grouped bars is depending on the highest occurence, I just want to know how to reverse the order of each group (the same order it would be as if I wouldn't use coord_flip).

zx8754
  • 52,746
  • 12
  • 114
  • 209
Revan
  • 2,072
  • 4
  • 26
  • 42
  • Possible duplicate of [reorder dodge bar plots (ggplot2)](https://stackoverflow.com/questions/33966908/reorder-dodge-bar-plots-ggplot2) – Maurits Evers Apr 10 '18 at 06:37
  • Have a look at [this post](https://stackoverflow.com/questions/33966908/reorder-dodge-bar-plots-ggplot2); the issue seems to be the identical, even with the same data. – Maurits Evers Apr 10 '18 at 06:38
  • I found this post before, that is actually where my question came from. Because in the last answer, the order is dependent on the highest occurence for each group of bars. However, I am trying to find out how to flip the order of the bars after using `coord_flip`. – Revan Apr 10 '18 at 06:42
  • `aes(x = Race, y = Words, fill = forcats::fct_rev(Film))`? – Axeman Apr 10 '18 at 08:44
  • The reason this happens, by the way, is that the groups are dodge increasing by x (now y), and (0, 0) is in the lower left hand corner. So the first group (red) is put closest to 0, which is lowest. – Axeman Apr 10 '18 at 08:58
  • `scale_x_discrete(limits=rev)` – Brian D May 27 '21 at 19:46

1 Answers1

3
p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position =  position_dodge2(reverse=TRUE)) +
coord_flip() 

Maybe you could start play with position_dodge2 function

Oldyoung
  • 567
  • 4
  • 8