Reordering x axis in barplot(ggplot2) where data is grouped on 2 variables

Viewed 369

In exploration of the mpg package in R, I want to plot a bar plot, of x variable as class, y variable as frequency values for class and then stack those bars with cyl.

So, I have first grouped the data set by class and cyl , then added freq for every group.

class_count <-
mpg %>% 
group_by(class,cyl) %>%
summarize(freq = n())

class_count %>%
  ggplot(aes(reorder(class,freq), freq, fill = cyl)) +
  geom_bar(stat= "identity")

I want the data to be ascending order but in the final plot subcompact bar is coming before pickup as shown in picture below -

bar plot for the code given above

enter image description here

Please help me to find a solution for this.

1 Answers

reorder sorts the bars solely based on freq without considering the class. Use fct_reorder

library(ggplot2)

ggplot(class_count, 
      aes(forcats::fct_reorder(class, freq, sum), freq, fill = cyl)) +
 geom_col() + xlab('class')

enter image description here

Related