Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder geom_bar from high to low when using stat="count"

Tags:

r

ggplot2

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.

like image 209
sagerbomb Avatar asked Jun 14 '19 13:06

sagerbomb


People also ask

How do you change the order of Barplots in R?

To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function.

How do you make a bar graph in descending order in R?

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.

What is Geom_bar stat?

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).

How do I change the width of a bar in ggplot2?

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.


Video Answer


2 Answers

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
like image 54
cicero Avatar answered Sep 21 '22 22:09

cicero


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))

enter image description here

like image 41
aosmith Avatar answered Sep 19 '22 22:09

aosmith