Reputation: 161
I want to reorder a geom_bar graph from high to low when using stat="count" so that I can apply a fill.
I tried using geom_bar(aes(x = reorder(x, -stat(count)), fill = type) but it didn't work and threw the error "Error: stat_count requires the following missing aesthetics: x"
library(ggplot2)
df <- data.frame(x = c("Bob", "James", "Mary", "Sally", "Timmy", "Sally", "Sally", "Bob", "Bob", "Mary"), type = c("A", "B", "A", "B", "B", "C", "B", "B", "A", "B"))
ggplot(df) +
geom_bar(aes(x = x, fill = type), stat = "count") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
I want the bars to be order from highest count on the left to lowest count on the right.
Upvotes: 16
Views: 18132
Reputation: 528
Here is a solution with reorder
from ggplot2 :
First, you need to count the occurence by names :
df2 <- df %>% group_by(x) %>% mutate(count_name_occurr = n())
Then when specifying x axis, you reorder x by descending name occurences.
g2<-ggplot(data=df2, aes(x=reorder(x,-count_name_occurr), fill=type)) +
geom_bar(stat="count")
g2
Upvotes: 12
Reputation: 36086
I'm not sure about a ggplot2 solution, but I would tackle this using the forcats package. There is a function fct_infreq()
to set the factor levels in order by frequency.
You could then do:
ggplot(df) +
geom_bar(aes(x = forcats::fct_infreq(x), fill = type)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
Upvotes: 18