如何在分组条形图上的所有条形组中订购条形图?

时间:2018-09-18 15:19:59

标签: r ggplot2

我正在用ggplot2制作分组条形图。我有这段代码...

ggplot(data = dummy,
       aes(
         fill = Geography2,
         x = Group,
         y = PunishmentRate
       )
) +
  geom_bar(
    position = "dodge",
    stat = "identity",
    width = 0.5
  ) +
  coord_flip() +
  geom_text(data = subset(dummy, Group == "White"),
            aes(
              label = Geography2,
              y = 0
            ),
            position = position_dodge(0.5),
            hjust = 0
  )

这就是这张图...

enter image description here

dummy数据框看起来像这样,以逗号分隔的格式...

Group,Enrollment,Punished,PunishmentRate,Geography2
Total,2001957,302878,0.1512909618,State
Black,436329,117791,0.2699591363,State
Hispanic,625588,72974,0.1166486569,State
White,855256,96396,0.1127101125,State
Total,151818,14159,0.0932629859,Local
Black,38933,6816,0.175069992,Local
Hispanic,53690,3789,0.0705718011,Local
White,53036,2925,0.055151218,Local

如何编辑代码,以使“本地”栏显示在“状态”栏之前?

1 个答案:

答案 0 :(得分:2)

尝试

dummy$Geography2 <- factor(dummy$Geography2, levels = c('State', 'Local'))

,然后重新运行该图。最低排序因数(当前为“本地”,因为如果按字母顺序排序,则位于“州”之前)。