R 如何将geom_文本元素对齐到第一个栏的中心?
我正在ggplot2中制作一个分组条形图,并希望将图例中的标签放在最顶部的条形图组中 我的数据框是逗号分隔格式的R 如何将geom_文本元素对齐到第一个栏的中心?,r,ggplot2,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.
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
)
输出的图表如下所示
我该如何做以下工作
要居中文本,只需使用
位置减淡(0.5)
而不是位置减淡(1)
。并且,要仅为第一个条形图子集提供文本,请提供geom_文本
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
)
导致: