sebastian fanchi
sebastian fanchi

Reputation: 39

How to sort bar plot in R

Im struggling with the order of a bar plot of mpg package, what i want is to plot the cty variable vs manufacturer, i have tried with reorder() and with fct_reorder() but i still have the same graph, this is what i have tried:

mpg <- ggplot2::mpg
#With fct_reorder
ggplot(mpg, aes(fct_reorder(manufacturer, cty), cty)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
#with reorder

ggplot(mpg,aes(x = reorder(manufacturer, -cty), y = cty)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

I get the plot but its still unordered by the cty values, what i am doing wrong?

Thanks for the help!

Upvotes: 0

Views: 68

Answers (2)

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

can simplify the proposed solution

ggplot(mpg,aes(x = reorder(manufacturer, -cty, sum), y = cty)) +
  geom_col() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Upvotes: 1

dave-edison
dave-edison

Reputation: 3736

The data you're passing isn't fully aggregated the way you want. This works:

library(dplyr)
library(ggplot2)

mpg %>% 
    group_by(manufacturer) %>% 
    summarise(cty = sum(cty)) %>% 
    ggplot(aes(x = reorder(manufacturer, -cty), y = cty)) +
    geom_col() +
    theme(axis.text.x = element_text(angle = 45, hjust = 1))

enter image description here

Upvotes: 1

Related Questions