Search code examples
rggplot2geom-bar

make geom_bar show values in the ascending order


Although my query shows me values in descending order, ggplot then displays them alphabetically instead of ascending order.

enter image description here

Known solutions to this problem haven't seem to work. They suggest using Reorder or factor for values, which didn't work in this case

This is my code:

boxoffice %>%
  group_by(studio) %>%
  summarise(movies_made = n()) %>%
  arrange(desc(movies_made)) %>%
  top_n(10) %>%
  arrange(desc(movies_made)) %>%
  ggplot(aes(x = studio, y = movies_made, fill = studio, label = as.character(movies_made))) +
  geom_bar(stat = 'identity') +
  geom_label(label.size = 1, size = 5, color = "white") +
  theme(legend.position = "none") +
  ylab("Movies Made") +
  xlab("Studio")

Solution

  • You'll need to convert boxoffice$studio to an ordered factor. ggplot will then respect the order of rows in the data set, rather than alphabetizing. Your dplyr chain will look like this:

    boxoffice %>%
      group_by(studio) %>%
      summarise(movies_made = n()) %>%
      arrange(desc(movies_made)) %>%
      ungroup() %>% # ungroup
      mutate(studio = factor(studio, studio, ordered = T)) %>% # convert variable
      top_n(10) %>%
      arrange(desc(movies_made)) %>%
      ggplot(aes(x = studio, y... (rest of plotting code)