gpt4 book ai didi

r - geom_text 如何根据需要在栏上定位文本?

转载 作者:行者123 更新时间:2023-12-03 10:23:33 24 4
gpt4 key购买 nike

我想调整条形图上的文本。

我尝试调整 hjust/vjust 以按我喜欢的方式显示,但它似乎无法正常工作。

ggplot(data) + 
geom_bar(aes(name, count,
fill = week), stat='identity', position = 'dodge') +
geom_text(aes(name,count,
label=count),hjust=0.5, vjust=3, size=2,
position = position_dodge(width = 1)) +
coord_flip()

enter image description here

所以我希望数字位于每个条形的中间、右边缘,这样它就可以阅读而不会像最后一部分那样重叠。

最佳答案

编辑:

获取更简单的解决方案 hjust/vjust聪明的行为就是添加 group审美到geom_text然后 hjust & position调整 group自动地。

1. 垂直方向

ggplot(data) + 
geom_bar(
aes(x = name, y = count, fill = week, group = week),
stat='identity', position = 'dodge'
) +
geom_text(
aes(x = name, y = count, label = count, group = week),
position = position_dodge(width = 1),
vjust = -0.5, size = 2
) +
theme_bw()

这给出:

enter image description here

2. 水平方向
ggplot(data) + 
geom_bar(
aes(x = name, y = count, fill = week, group = week),
stat='identity', position = 'dodge'
) +
geom_text(
aes(x = name, y = count, label = count, group = week),
hjust = -0.5, size = 2,
position = position_dodge(width = 1),
inherit.aes = TRUE
) +
coord_flip() +
theme_bw()

这给出:

enter image description here

这不一定是执行此操作的最通用方法,但您可以使用 fill受抚养人 hjust (或 vjust ,取决于方向)变量。我不太清楚如何选择调整参数的值,目前它是基于看起来正确的。也许其他人可以建议一种更通用的选择此参数值的方法。

1. 垂直方向
library(dplyr)
library(ggplot2)

# generate some data
data = data_frame(
week = as.factor(rep(c(1, 2), times = 5)),
name = as.factor(rep(LETTERS[1:5], times = 2)),
count = rpois(n = 10, lambda = 20),
hjust = if_else(week == 1, 5, -5),
vjust = if_else(week == 1, 3.5, -3.5)
)

# Horizontal
ggplot(data) +
geom_bar(
aes(x = name, y = count, fill = week, group = week),
stat='identity', position = 'dodge'
) +
geom_text(
aes(x = name, y = count, label = count, vjust = vjust),
hjust = -0.5, size = 2,
inherit.aes = TRUE
) +
coord_flip() +
theme_bw()

这是它的样子:

enter image description here

2. 水平方向
ggplot(data) + 
geom_bar(
aes(x = name, y = count, fill = week, group = week),
stat='identity', position = 'dodge'
) +
geom_text(
aes(x = name, y = count, label = count, vjust = vjust),
hjust = -0.5, size = 2,
inherit.aes = TRUE
) +
coord_flip() +
theme_bw()

这是它的样子:

enter image description here

关于r - geom_text 如何根据需要在栏上定位文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40211451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com