代码之家  ›  专栏  ›  技术社区  ›  zoowalk

在条形图中使用位置闪避(preserve=“single”)时,几何图形文本位置不正确

  •  3
  • zoowalk  · 技术社区  · 8 年前

    由于下面的代码,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")
    

    enter image description here

    更新/回答: 使用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")
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Z.Lin    8 年前

    如果这个例子与您的实际用例类似,我建议您避免使用 position_dodge ,只需将不同的变量分配给 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())
    

    plot

    推荐文章