1

我的条形图代码:

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,它有什么问题?)

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

4

1 回答 1

2

有条件的hjust可能会有所帮助。请注意,这hjust = "inward/outward"意味着“相对于情节的中心” -请参阅本讨论中 Hadley 的评论

规模扩张=这是体力劳动。对于编程方法,您需要访问 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))

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

于 2021-03-07T20:18:48.100 回答