Datatician
Datatician

Reputation: 15

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")

Upvotes: 0

Views: 1164

Answers (2)

Sam Mason
Sam Mason

Reputation: 16174

for those wanting a more complete example, here's where I got:

library(dplyr)
library(ggplot2)

# get some dummy data
boxoffice = boxoffice::boxoffice(dates=as.Date("2017-1-1"))

df <- (
  boxoffice %>%
  group_by(distributor) %>%
  summarise(movies_made = n()) %>%
  mutate(studio=reorder(distributor, -movies_made)) %>%
  top_n(10))

ggplot(df, aes(x=distributor, y=movies_made)) + geom_col()

Upvotes: 1

jdobres
jdobres

Reputation: 11957

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)

Upvotes: 0

Related Questions