Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add means to a ggplot + geom_point plot

Tags:

r

ggplot2

I have 10 groups of data points and I am trying to add the mean to for each group to be displayed on the plot (e.g. by a different symbol such as a big triangle or a star or something similar). Here is a reproducible example

library(ggplot2)
library(reshape2)
set.seed(1234)

x <- matrix(rnorm(100),10,10)
varnames <- paste("var", seq(1,10))

df <- data.frame(x)
colnames(df) <- varnames
melt(df)

ggplot(data = melt(df)) + geom_point(mapping = aes(x = variable, y = value))
mymeans <- colMeans(df)

Basically I now want to have the values in mymeans plotted in their respective variable location, would anybody have an idea how to quickly do this?

like image 391
Jean_N Avatar asked Dec 01 '22 10:12

Jean_N


1 Answers

Or we can use stat_summary

ggplot(data = reshape2::melt(df), aes(x = variable, y = value)) + 
  geom_point() +
  stat_summary(
    geom = "point",
    fun.y = "mean",
    col = "black",
    size = 3,
    shape = 24,
    fill = "red"
  )

enter image description here


An overview about possible shapes can be found here: www.cookbook-r.com

like image 183
markus Avatar answered Dec 04 '22 00:12

markus