zoo*_*alk 5 r ggplot2 geom-text
使用下面的代码,刻面 bB 中的标签未正确定位。问题似乎源于这样一个事实,即没有position_dodge(preserve="single")for 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")
Run Code Online (Sandbox Code Playgroud)
更新/答案:使用 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")
Run Code Online (Sandbox Code Playgroud)
如果该示例与您的实际用例类似,我建议避免使用 的所有这些麻烦position_dodge,而只需将不同的变量分配给 的 x 轴和列facet_grid。您当前对两者都使用“Var2”。
ggplot(df,
aes(x = Var3, y = val)) + # put Var3 here instead of Var2
geom_col(aes(fill = Var3)) + # dodge becomes unnecessary here
geom_text(aes(y = val + 1, label = val)) + # as above
facet_grid(Var1 ~ Var2) +
# optional, simulates the same appearance as original
labs(x = "Var2") +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |