我的条形图代码:
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,它有什么问题?)
那么如何结合第二个和第三个解决方案,使所有标签都在条形之外并且可见?