【发布时间】:2019-01-19 16:28:08
【问题描述】:
使用下面的代码,刻面 bB 中的标签位置不正确。
问题似乎源于geom_text 没有position_dodge(preserve="single") 的事实(正确吗?)。我知道我可以“手动”添加一个空的虚拟单元格(在构面 bB 中填充 y=0),但我想知道是否有任何方法可以直接在 ggplot 中对其进行更正?
v1 <- LETTERS[1:2]
v2 <- letters[1:2]
v3 <- c("x","y")
g <- expand.grid(v1,v2,v3)
val=c(sample(10,8))
df<- data.frame(g,val)
df<- df[-8,]
df %>% ggplot() +
geom_bar(aes(x=Var2, y=val, fill=Var3, group=Var3),
stat="identity",
position=position_dodge(preserve="single"))+
geom_text(aes(x=Var2, y=val+1, label=val, group=Var3),
position=position_dodge(width=1))+
facet_grid(Var1~Var2, scale="free_x")
更新/回答:使用 position_dodge2 将条与标签对齐(但是,条是居中的,而不是与其他方面的条对齐)。
df %>% ggplot() +
geom_bar(aes(x=Var2, y=val, fill=Var3, group=Var3), stat="identity",
position=position_dodge2(preserve="single"))+
geom_text(aes(x=Var2, y=val+1, label=val, group=Var3),
position=position_dodge2(width=1))+
facet_grid(Var1~Var2, scale="free_x")
【问题讨论】: