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()
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()
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.
Such an obvious solution and I hadn’t connected to it.
– Marcus Nunes