将geom_text放置在geom_col堆叠的条形图中每个条形段的中间 [英] Position geom_text in the middle of each bar segment in a geom_col stacked barchart
问题描述
我想将相应的值标签放置在每个条形段中间的geom_col
堆叠条形图中.
I would like to position the corresponding value labels in a geom_col
stacked barchart in the middle of each bar segment.
但是,我的幼稚尝试失败了.
However, my naive attempt fails.
library(ggplot2) # Version: ggplot2 2.2
dta <- data.frame(group = c("A","A","A",
"B","B","B"),
sector = c("x","y","z",
"x","y","z"),
value = c(10,20,70,
30,20,50))
ggplot(data = dta) +
geom_col(aes(x = group, y = value, fill = sector)) +
geom_text(position="stack",
aes(x = group, y = value, label = value))
很明显,将y=value/2
设置为geom_text
也无济于事.此外,文本的位置顺序错误(颠倒了).
Obviously, setting y=value/2
for geom_text
does not help, either. Besides, the text is positioned in the wrong order (reversed).
任何(优雅的)想法如何解决这个问题?
Any (elegant) ideas how to solve this?
推荐答案
您需要将一个变量映射到一个美学对象,以表示geom_text
中的组.对于您来说,这是您的"sector"变量.您可以将其与geom_text
中的group
美感搭配使用.
You need to have a variable mapped to an aesthetic to represent the groups in geom_text
. For you, this is your "sector" variable. You can use it with the group
aesthetic in geom_text
.
然后使用position_stack
和vjust
将标签居中.
Then use position_stack
with vjust
to center the labels.
ggplot(data = dta) +
geom_col(aes(x = group, y = value, fill = sector)) +
geom_text(aes(x = group, y = value, label = value, group = sector),
position = position_stack(vjust = .5))
您可以通过全局设置美学来节省一些打字.然后fill
将用作geom_text
的分组变量,您可以跳过group
.
You could save some typing by setting your aesthetics globally. Then fill
would be used as the grouping variable for geom_text
and you can skip group
.
ggplot(data = dta, aes(x = group, y = value, fill = sector)) +
geom_col() +
geom_text(aes(label = value),
position = position_stack(vjust = .5))
这篇关于将geom_text放置在geom_col堆叠的条形图中每个条形段的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!