【问题标题】:Position labels in geom_col() outside of bars在条形之外的 geom_col() 中定位标签
【发布时间】:2021-03-07 20:06:52
【问题描述】:

我的条形图代码:

library(ggplot2)
data <- data.frame(vars = c("pos1", "neg1", "pos2", "neg2", "pos3", "pos4"), 
                   values = c(164182, -72705, 1023777, -75002, 756206, 564523),
                   sign = c("p", "n", "p", "n", "p", "p"))
ggplot(data, aes(x = values, y = vars, fill = sign)) + geom_col() + 
  geom_text(aes(label = format(round(values), big.mark = ",")))

不错,但我希望标签位于条形之外,并且完全可见。在上面的示例中,我让它们“半进半出”,pos2 的标签不完全可见。

所以我在最后一行添加了 hjust = "outward":

library(ggplot2)
data <- data.frame(vars = c("pos1", "neg1", "pos2", "neg2", "pos3", "pos4"), 
                   values = c(164182, -72705, 1023777, -75002, 756206, 564523),
                   sign = c("p", "n", "p", "n", "p", "p"))
ggplot(data, aes(x = values, y = vars, fill = sign)) + geom_col() + 
  geom_text(aes(label = format(round(values), big.mark = ",")), hjust = "outward")

现在除了 pos1 之外的所有标签(为什么会这样?)完全符合我想要的(外部),但其中三个超出了界限,这不好。 将“向外”更改为“向内”解决了“越界”问题,但标签现在位于条形内部(除了 pos1,它有什么问题?)

那么如何结合第二个和第三个解决方案,使所有标签都在条形之外并且可见?

【问题讨论】:

    标签: r ggplot2 label geom-text geom-col


    【解决方案1】:

    有条件的hjust 可能会有所帮助。请注意,hjust = "inward/outward" 表示“相对于绘图中心” - see Hadley's comment in this discussion

    规模扩张 = 这是体力劳动。对于编程方法,您需要访问 geom_text 维度,这似乎非常困难 - see this unanswered question

    library(ggplot2)
    data <- data.frame(vars = c("pos1", "neg1", "pos2", "neg2", "pos3", "pos4"), 
                       values = c(164182, -72705, 1023777, -75002, 756206, 564523),
                       sign = c("p", "n", "p", "n", "p", "p"))
    ggplot(data, aes(x = values, y = vars, fill = sign)) + geom_col() + 
      geom_text(aes(label = values),
                hjust = ifelse(data$values>0,0,1))+
      scale_x_continuous(expand = c(.3,0))
    

    reprex package (v1.0.0) 于 2021-03-07 创建

    【讨论】:

    • 谢谢,这绝对是一种改进。有没有办法“扩展”面板,这样标签会留在里面,不会像红条那样与轴-y标签发生碰撞?
    • @АндрійzOFsky 不是以编程方式 - 请参阅这个未回答的问题 stackoverflow.com/questions/55686910/…
    • 谢谢@tjebo,你是救世主!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多