I want to plot only once the text of the mean for the specific cluster.
So I have followed plot:

but what I want is this:

code for reproduction:
price_l <- rep(c('€€-€€€', '€€-€€€', '€€€€', '€€-€€€', '€€-€€€',
'€€-€€€', '€€€€', '€€-€€€', '€€€€', '€€-€€€',
'€€-€€€', '€€-€€€', '€€-€€€', '€€-€€€',
'€€-€€€', '€€-€€€', '€€-€€€', '€€-€€€', '€€€€','€', '€',
'€', '€','€€€€', '€'),100)
avg_r <- rep(c(4.5, 3.5, 4.0, 4.0, 4.0, 3.5, 4.5, 4.0, 3.0, 4.0,
3.0, 5.0, 4.5, 4.0, 3.0,
3.5, 4.5, 3.5, 3.5, 4.0, 3.0, 4.0, 4.0, 2.5, 4.5),100)
sub.df <- data.frame(price_l, avg_r)
sub.df %>%
group_by(price_l) %>%
mutate(mean = mean(avg_r)) %>%
ungroup() %>%
ggplot(sub.df, mapping=aes(price_l, avg_r), na.rm=T) +
geom_jitter(aes(colour = price_l)) +
geom_text(aes(label = sprintf("%.2f",mean)))
You can set the y value manually inside the geom_text
sub.df %>%
group_by(price_l) %>%
mutate(mean = mean(avg_r)) %>%
ungroup() %>%
ggplot(sub.df, mapping=aes(price_l, avg_r), na.rm=T) +
geom_jitter(aes(colour = price_l)) +
geom_text(aes(y = 3.5, label = sprintf("%.2f",mean)),
check_overlap = TRUE, size = 6, fontface = 2)

Or, as r2evans suggests:
sub.df %>%
group_by(price_l) %>%
mutate(mean = mean(avg_r)) %>%
ungroup() %>%
ggplot(sub.df, mapping=aes(price_l, avg_r), na.rm=T) +
geom_jitter(aes(colour = price_l)) +
geom_text(aes(y = mean, label = sprintf("%.2f",mean)),
check_overlap = TRUE, size = 6, fontface = 2)

We could use stat_summary(aes(label = ..y..), geom = "text", fun = mean, color="black", size = 6, fontface = 2)
sub.df %>%
group_by(price_l) %>%
mutate(mean = mean(avg_r)) %>%
ungroup() %>%
ggplot(sub.df, mapping=aes(price_l, avg_r), na.rm=T) +
geom_jitter(aes(colour = price_l)) +
stat_summary(aes(label = ..y..), geom = "text", fun = mean, color="black", size = 6, fontface = 2)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With