-1

I have a following code, where I would like to do a bar plot from XXX dataset, where X2 variable is sorted:

XXX %>% arrange(desc(X2)) %>%
   ggplot(aes(x = X1, y = X2)) +
   geom_bar(stat = "identity", width =  0.75) + 
   coord_flip()

Why it does not work? I have the same plot like without arrange(desc(X2)). I know already how to do the arrangement, but I would like to understand why it is not an appropriate solution.

ltrd
  • 326
  • 1
  • 8
  • Possible duplicate of [How do you order the fill-colours within ggplot2 geom\_bar](https://stackoverflow.com/questions/15251816/how-do-you-order-the-fill-colours-within-ggplot2-geom-bar) – RLave Aug 24 '18 at 07:46
  • RLave, I said that I know how to do it. I would like to understand why it does not work. So I think it is not a duplicated question. – ltrd Aug 24 '18 at 07:48
  • https://github.com/tidyverse/ggplot2/issues/721 – RLave Aug 24 '18 at 07:48
  • From the answer to that other question. – RLave Aug 24 '18 at 07:49
  • What is your expected output and what is your actual output? `arrange` shouldn't affect the order of the bars in the plot – Chris Aug 24 '18 at 08:02

1 Answers1

2

arrange() just sorts the data but ggplot does do it's own sorting. This is convenient if X2 is numeric but might be somewhat unexpected for text. The trick is to define X2 in a way, that the natural order of X2 is the order you want. If you want for example X2 ordered by decreasing frequencies, you could write your own function e.g.:

factor_freq <- function(x, decreasing = TRUE) {
  counts <- sort(table(x), decreasing = decreasing)
  factor(x, levels=names(counts))
}

and then

XXX %>% mutate(X2 = factor_freq(X2)) %>%
   ggplot(aes(x = X1, y = X2)) +
   geom_bar(stat = "identity", width =  0.75) + 
   coord_flip()

should produce the desired plot.