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.
To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function.
Rearranging Results in Basic R Then draw the bar graph of the new object. If you want the bar graph to go in descending order, put a negative sign on the target vector and rename the object. Then draw the bar graph of the new object.
geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights).
To Increase or Decrease width of Bars of BarPlot, we simply assign one more width parameter to geom_bar() function. We can give values from 0.00 to 1.00 as per our requirements.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With