由于下面的代码,bB面标签位置不正确。
问题似乎源于
position_dodge(preserve="single")
对于
geom_text
(对吗?)。我知道我可以“手动”添加一个空的虚拟单元格(在facet 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")