这个问题在这里已经有了答案:
Showing data values on stacked bar chart in ggplot2
(2 个回答)
4年前关闭。
我想在 geom_col
中放置相应的值标签每个条形段中间的堆积条形图 .
然而,我天真的尝试失败了。
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
也无济于事。此外,文本以错误的顺序定位(颠倒)。任何(优雅的)想法如何解决这个问题?
最佳答案
您需要将变量映射到美学来表示 geom_text
中的组。 .对您来说,这是您的“部门”变量。您可以将它与 group
一起使用美学在 geom_text
.
然后使用 position_stack
与 vjust
使标签居中。
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
.ggplot(data = dta, aes(x = group, y = value, fill = sector)) +
geom_col() +
geom_text(aes(label = value),
position = position_stack(vjust = .5))
关于r - 将 geom_text 放置在 geom_col 堆叠条形图中每个条形段的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724142/