Reputation: 39
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
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
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))
Upvotes: 1