ggplot2 boxplot stat_summary text placement by group

…衆ロ難τιáo~ 提交于 2019-12-23 03:07:05

问题


In the plot below, I'd like the number of observations (40 in this case) to be overlayed on top of each boxplot. My code below doesn't work when there's a fill aesthetic. The text need to be adjusted horizontally (1 left, 1 center, 1 right in this case) so that they properly overlay their corresponding boxplots.

dt <- data.table(
    x = factor(rep(1:2, each=120))
    , f = rep(letters[1:3], 40)
    , y = c(rnorm(120, 1:3), rnorm(120, 1:3*2))
)
table(dt$x, dt$f)

+--------------+
|      a  b  c |
+--------------+
|   1 40 40 40 |
|   2 40 40 40 |
+--------------+

frequencyAnnotation <- function(x) {
   c(y = (quantile(x, .75, names = F) + median(x))/2, label=length(x))
}
ggplot(dt, aes(x=x, y=y, fill=f)) +
    geom_boxplot() +
    stat_summary(fun.data = frequencyAnnotation, geom='text')


回答1:


As your boxplots are dodged when you use argument fill=, you have to add position_dodge() to the stat_summary() call.

ggplot(dt, aes(x=x, y=y, fill=f)) +
      geom_boxplot() +
      stat_summary(fun.data = frequencyAnnotation, geom='text', 
                   position = position_dodge(width = 0.75)) 


来源:https://stackoverflow.com/questions/43414864/ggplot2-boxplot-stat-summary-text-placement-by-group

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