我想调整小节上的文字。
我尝试调整“调整/调整”以使其按自己的喜好显示,但似乎无法正常工作。
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()
因此,我希望数字位于每个条形图的右边缘中间,以便其可读性而不会像最后一部分那样重叠。
最佳答案
编辑:
使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()
这给出:
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()
这给出:
这不一定是执行此操作的最通用方法,但是您可以拥有一个依赖
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()
看起来像这样:
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()
看起来像这样:
关于r - geom_text如何根据需要在栏上放置文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40211451/