How to display mean for each group in point chart using ggplot2 in R?


To display mean for each group in point chart using ggplot2 in R, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use geom_point and geom_summary functions and provide mean for fun argument with different size and shape of the point for mean display.

Example

Create the data frame

Let’s create a data frame as shown below −

grp<-sample(LETTERS[1:5],25,replace=TRUE)
dv<-sample(1:50,25)
df<-data.frame(grp,dv)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  grp dv
1  E  25
2  E  29
3  E  24
4  E  45
5  B  48
6  A  17
7  C  22
8  D   6
9  A  10
10 E  34
11 A  19
12 C  30
13 B  36
14 E  28
15 D  38
16 E  32
17 E  39
18 A  43
19 B   7
20 C   2
21 D   4
22 D   3
23 A  46
24 D  16
25 A  47

Display mean for each group in point chart using ggplot2

Using geom_point and geom_summary functions and provide mean for fun argument with different size and shape of the point for mean display for the data stored in data frame df as shown below −

grp<-sample(LETTERS[1:5],25,replace=TRUE)
dv<-sample(1:50,25)
df<-data.frame(grp,dv)
library(ggplot2)

ggplot(df,aes(grp,dv))+geom_point()+stat_summary(geom="point",fun="mean",shape=24,fill="blue",size=4)

Output

Updated on: 15-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements