Reorder the columns of a bar chart and its caption

Asked

Viewed 655 times

1

When processing and plotting data in R using tidyverse, it by default leaves the chart bar order in the original column factor order:

library(tidyverse)

mpg$trans <- as.factor(mpg$trans)

mpg %>%
  group_by(trans) %>%
  count(trans) %>%
  ggplot(., aes(x = trans, y = n, fill = trans)) +
  geom_col()

inserir a descrição da imagem aqui

I would like the bars to appear ordered by their frequency. I had already asked a similar question here, but at the time I had not considered the case with caption. So, by using the solution of this question, I get the result below:

mpg %>%
  group_by(trans) %>%
  count(trans) %>%
  ggplot(., aes(x = reorder(trans, n), y = n, fill = trans)) +
  geom_col()

inserir a descrição da imagem aqui

Note the use of the function reorder within the function ggplot to leave the bars in the order I wish. However, the order of the items in the legend trans continues in the original order of the factor levels.

What I would like is for the bars to be in an order identical to the one shown in the previous chart, with the caption in the same order. In the CMR above, the order of the legend should be

  • auto(L3)
  • auto(S4)
  • auto(S5) ...
  • manual(M5)
  • auto(L4)

How can I do this in an automated way? That is, without having to define the levels of the factor trans manually?

Disregard the caption of the superimposed x-axis. I ended up not fixing this in my example, but the final version of the chart will have this problem solved.

1 answer

1


You can pull the reorder for a mutate, then already fix the bars and subtitles at once.

library(tidyverse)

mpg %>%
  group_by(trans) %>%
  count(trans) %>%
  ungroup() %>% 
  mutate(trans = reorder(trans, n)) %>% 
  ggplot(., aes(x = trans, y = n, fill = trans)) +
  geom_col()

Created on 2020-03-23 by the reprex package (v0.3.0)

  • 1

    Such an obvious solution and I hadn’t connected to it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.