【问题标题】:geom_text not properly positioned when using position_dodge(preserve="single") in bar plot在条形图中使用 position_dodge(preserve="single") 时 geom_text 未正确定位
【发布时间】: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")

【问题讨论】:

    标签: r ggplot2 geom-text


    【解决方案1】:

    如果示例与您的实际用例相似,我建议使用position_dodge 避免所有这些麻烦,而只需将不同的变量分配给facet_grid 的x 轴和列。您目前对两者都使用“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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多