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

使用ggplot调整geom_文本和条形图之间的距离

  •  0
  • Haakonkas  · 技术社区  · 6 年前

    我有一个表示相关值的图,我表示每个条上有一个星的显著相关。但是,我似乎不能增加星和条之间的距离,因为条在图中是双向的(有些值是负的,另一些是正的)。我想知道如何增加相同数量的文字距离,只是在不同的方向。 Nudge_x nudge_y 将只更改绘图中一个方向上的所有点。此外,文本标签似乎不在每个栏的中心。

    例子:

    df <- structure(list(ref2 = c("A", "B", "C", "D", "E"), estimate = c(-0.220522748118839, 
    -0.179731936253906, 0.0400276364582935, -0.568250677328796, 0.189980289483266
    ), sign = c("*", "*", NA, "*", "*")), row.names = c(NA, -5L), class = c("tbl_df", 
    "tbl", "data.frame"))
    
    library(ggplot2)
    
    ggplot(df, aes(ref2, estimate)) +
      geom_col() +
      geom_text(aes(label = sign),
                size = 10) +
      coord_flip()
    
    

    结果如下:

    enter image description here

    我想结束的是:

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  2
  •   Jon Spring    6 年前

    vjust hjust 应该有帮助:

    ggplot(df, aes(ref2, estimate)) +
      geom_col() +
      geom_text(aes(label = sign), 
                hjust = ifelse(df$estimate < 0, 1.5, -0.5),
                vjust = 0.75,
                size = 10) +
      coord_flip()
    

    enter image description here

        2
  •  0
  •   howardG    6 年前

    您可以创建一个新的数据帧,该数据帧接受df$estimate的每行的符号,并将其乘以offsetfactor。然后,这个列/数组可以基本上充当GeOMXML文本的一个新的偏移y轴,从而给你想要的效果。

    df2 <- data.frame(df$estimate) %>% mutate(newEstimate = df$estimate + sign(df$estimate)*0.03)
    
    ggplot(df, aes(ref2, estimate)) +
      geom_col() +
      geom_text(aes(y = df2[,2], label = sign), size = 10) +
      coord_flip()
    
    推荐文章