且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ggplot2:如果位置="fill",则在条形图上添加标签.

更新时间: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.