如何在第一栏的中心对齐geom_text元素?

时间:2018-09-18 04:11:53

标签: r ggplot2

我正在ggplot2中制作一个分组的条形图,并希望将图例中的标签放在最上面的条形组中。

我的数据框看起来像这样,以逗号分隔。

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

在我的R脚本中,此数据帧位于变量dummy中。

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

输出的图表如下所示。

enter image description here

我该如何执行以下操作?

  1. 在栏的中间垂直放置“状态”和“本地”?
  2. 仅显示第一个条形组(最上面的组)的标签吗?

1 个答案:

答案 0 :(得分:1)

要使文本居中,只需使用position_dodge(0.5)而不是position_dodge(1)。并且只为第一个条形子集的文本提供数据框geom_text

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