我无法弄清楚如何在ggplot2
的条形图中以每个躲避条形为中心显示标签。
我知道我可以使用position = "dodge"
躲避酒吧,我知道为了让标签以每个栏为中心显示,我需要在position = position_dodge(width = 1)
中添加geom_text()
或geom_label()
命令。
但由于某种原因,它不起作用(见下图)。我还添加了我的数据和代码。
df <- structure(list(Measure = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1988",
"2017"), class = "factor"), Province = structure(c(1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L), .Label = c("BC", "AB", "SK", "MB", "ON", "QC", "NB",
"PE", "NS", "NL"), class = "factor"), Value = c(363L, 61L, NA,
69L, NA, NA, 127L, 12L, 92L, 18L, 178L, 29L, 41L, 92L, 284L,
1019L, 267L, 27L, 77L, 22L)), .Names = c("Measure", "Province",
"Value"), row.names = 41:60, class = "data.frame")
ggplot(df, aes(x=Province, y=Value)) + geom_bar(aes(fill=Measure), position="dodge",
stat="identity") + geom_label(aes(label=Value), position = position_dodge(width=1))
答案 0 :(得分:2)
试试这个
ggplot(df, aes(x=Province, y=Value, group = Measure)) +
geom_col(aes(fill=Measure),
position ="dodge", width = 0.4)+
geom_text(aes(label= Value,
group = Measure
),vjust= 0, position = position_dodge(0.4) , color="black" )
答案 1 :(得分:2)
我刚刚意识到(感谢@aelwan回答)我唯一需要做的就是在group=Measure
函数中添加aes()
,即
ggplot(df, aes(x=Province, y=Value, group=Measure)) +
geom_bar(aes(fill=Measure),position="dodge", stat="identity") +
geom_label(aes(label=Value),position = position_dodge(width=1))
这给出了:
答案 2 :(得分:0)
这是一个较晚的答案,但是geom_text并非在条形图上居中。解决此问题的一种方法是也指定条形position=position_dodge(width = 1)
的宽度。
geom_bar(aes(fill=Measure),position=position_dodge(width = 1), stat="identity")