首页 > 解决方案 > How can I order the bars in my histogram?

问题描述

I've looked at, for example, "Order Bars in ggplot2 bar graph" and "How to reorder the groups in a grouped bar-chart [duplicate]". But I haven't been able to adapt those to my problem.

I'm trying to make a very basic histogram, with the bars being the number of models in each class and being ordered by that number:

library(ggplot2)

mpg %>%
  ggplot +
  geom_bar(mapping = aes(
    x = reorder(class, count)
  ))

I can make the unordered version work:

mpg %>%
  ggplot +
  geom_bar(mapping = aes(
    x = class
  ))

Can anyone help? What am I doing wrong? Is there a way to order that factor by count?

标签: rggplot2

解决方案


使用forcats包:

library(forcats)
library(ggplot2)

ggplot(mpg, aes(fct_infreq(class))) + 
  geom_bar()

在此处输入图像描述


推荐阅读