问题
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