简体   繁体   English

Position 标签在条形之外的 geom_col()

[英]Position labels in geom_col() outside of bars

Code for my bar plot:我的酒吧代码 plot:

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 = ",")))

结果我得到:

Not bad, but I want labels to be just outside of the bars and be fully visible .不错,但我希望标签位于条形之外并且完全可见 In the example above I have them "half in half out", label for pos2 is not fully visible.在上面的示例中,我让它们“半进半出”,pos2 的 label 不完全可见。

So I added hjust = "outward" in the last line:所以我在最后一行添加了 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")

结果

Now all labels except pos1 (and why is that?) are exactly as I want them (outside) but three of them are out of bounds which is not good.现在除了 pos1 之外的所有标签(为什么会这样?)完全符合我想要的(外部),但其中三个超出了界限,这是不好的。 Changing "outward" to "inward" solves "out of bounds" problem, but labels are now inside of bars(except pos1, what's wrong with it?)将“向外”更改为“向内”解决了“越界”问题,但标签现在位于条形内部(除了 pos1,它有什么问题?) “向内”选项

So how do I combine second and third solution so all labels are outside of the bars and visible?那么如何结合第二个和第三个解决方案,使所有标签都在条形之外并且可见?

A conditional hjust might help.有条件的hjust可能会有所帮助。 Note that hjust = "inward/outward" means "relative to the centre of the plot" - see Hadley's comment in this discussion请注意, hjust = "inward/outward"的意思是“相对于情节的中心” - 请参阅本讨论中 Hadley 的评论

scale expansion = this is manual labour.规模扩张=这是体力劳动。 For a programmatic approach, you would need to access the geom_text dimensions, which seems very difficult - see this unanswered question对于编程方法,您需要访问 geom_text 维度,这似乎非常困难 - 请参阅这个未回答的问题

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))

Created on 2021-03-07 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 3 月 7 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM