ggplot2: How to Plot Mean Values with geom_bar
geom_bar()
is a function in the ggplot2 package which widely used for creating barplots.
Many times you need to visualize the mean of the data using the barplot. The geom_bar()
is particularly useful for visualizing
the mean of the data without manually calculating it.
The basic command of geom_bar()
to visualize the mean using barplot is:
# load package
library(ggplot2)
ggplot(df, aes(group, value)) + geom_bar(stat='summary')
By default, the stat='summary'
argument in geom_bar()
calculates the mean for each group in
the data frame.
The following example demonstrates how to use geom_bar()
to visualize the mean using barplot.
1 Plot mean values with geom_bar
Create a sample data frame for two groups,
# create sample data frame
df <- data.frame(
groups = rep(c("drug", "placebo"), each = 10),
value = c(rnorm(10, mean = 5),
rnorm(10, mean = 12))
)
# view data
head(df)
groups value
1 drug 4.750353
2 drug 2.511782
3 drug 5.547362
4 drug 5.610277
5 drug 3.518247
6 drug 5.725951
The data frame df
has two groups drug and placebo, and their measured values.
We want to use this data frame to create the barplot with the mean value for each group.
# load package
library(ggplot2)
# create barplot
ggplot(data=df, aes(groups, value)) + geom_bar(stat='summary')
We have created the barplot using mean values using the geom_bar()
function.
Now, let’s calculate the mean for each group and compare it with the barplot.
You can use the built-in aggregate()
function in R to calculate the mean of each group in a data frame.
# calculate the mean of each group
aggregate(value ~ groups, df, mean)
groups value
1 drug 4.642326
2 placebo 11.995898
The mean value of drug and placebo groups are 4.64 and 11..99, respectively. These mean values for each group match to the height of the bars