編集:
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()
これは次のようになります。
