ggplot2: Add label on barplot if position = “fill”

偶尔善良 提交于 2019-12-06 04:51:26
aosmith

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")

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!