gos*_*osz 10 r ggplot2 stacked-chart geom-text
我想将相应的值标签放在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))
Run Code Online (Sandbox Code Playgroud)
显然,设置y=value/2为geom_text不帮助,无论是.此外,文本的顺序错误(反向).
任何(优雅的)想法如何解决这个问题?
aos*_*ith 28
你需要有一个映射到美学的变量来表示中的组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))
Run Code Online (Sandbox Code Playgroud)
您可以通过全局设置美学来节省一些打字.然后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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10127 次 |
| 最近记录: |