更新时间:2022-06-26 09:34:43
To avoid creating the position values yourself, you can use position = "stack"
in geom_text
as in this question. As you noted in the comments, the dataset must be ordered by the fill
variable to get the stacks in the correct order to match the bar stacks.
ggplot(x0, aes(grp, weight = n)) +
geom_bar(aes(fill = out), position = "fill") +
facet_grid(.~treat) +
scale_y_continuous(labels=percent) +
geom_text(aes(label = p2, y=p), position = "stack")
您最终可能需要删除一定尺寸以下的标签,以删除上图中的重叠部分. geom_text(aes(label = ifelse(p < .05, NA, p2), y = p), position = "stack")
之类的东西会删除非常小的值的标签.
You may end up needing to remove the labels below a certain size to remove the overlap seen in the plot above. Something like geom_text(aes(label = ifelse(p < .05, NA, p2), y = p), position = "stack")
would remove labels for the very small values.