R ggplot 组内的排序条

kan*_*and 5 r ggplot2

我正在尝试在 R 中格式化分组条形图ggplot,使条形按每组递减的顺序排列。这是我目前的情节:

当前图表

基于此数据框:

> top_categories
                    Category Count Community
1         Singer-Songwriters   151         1
2          Adult Alternative   147         1
3                  Dance Pop    95         1
4                       Folk    89         1
5         Adult Contemporary    88         1
6                    Pop Rap   473         2
7         Gangsta & Hardcore   413         2
8                       Soul   175         2
9                 East Coast   170         2
10                West Coast   135         2
11 Album-Oriented Rock (AOR)   253         3
12        Singer-Songwriters   217         3
13                 Soft Rock   196         3
14                      Folk   145         3
15        Adult Contemporary   106         3
16                      Soul   278         4
17                     Blues   137         4
18                      Funk   119         4
19               Quiet Storm    76         4
20                 Dance Pop    74         4
21             Indie & Lo-Fi   235         5
22                Indie Rock   234         5
23         Adult Alternative   114         5
24          Alternative Rock    49         5
25        Singer-Songwriters    47         5
Run Code Online (Sandbox Code Playgroud)

使用此代码创建:

ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Category,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)
Run Code Online (Sandbox Code Playgroud)

根据相关帖子的建议,我尝试使用该reorder函数并将其Count转化为一个因素,结果似乎都打破了条形与文本的顺序,或者以一种荒谬的方式重新调整了情节,例如(与因素):

混乱的因子图

关于如何完成此组内订购的任何提示?谢谢!

Lam*_*mia 6

当您按类别分组时,条形将根据类别在数据框中的出现顺序进行排序。这适用于社区 1 和 2,因为您的行已经通过减少计数进行排序。但是在社区 3 中,由于类别“歌手-歌曲作者”是数据框中第一个出现的类别,因此将其放在首位。

通过 Id 变量分组可以解决问题:

top_categories$Id=rep(c(1:5),5)

ggplot(
  top_categories,
  aes(
    x=Community,
    y=Count,
    group=Id,
    label=Category
  )
) +
  geom_bar(
    stat="identity",
    color="black",
    fill="#9C27B0",
    position="dodge"
  ) +
  geom_text(
    angle=90,
    position=position_dodge(width=0.9),
    hjust=-0.05
  ) +
  ggtitle("Number of Products in each Category in Each Community") +
  guides(fill=FALSE)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明