[R] How to generate side-by-side R barplot with errorbar using ggplot

ggplot2 is an R graphics framework that can be used to generate almost any type of chart. The plots generated using ggplot2 look very elegant and aesthetically pleasing. When you create a plot using ggplot, you can start with a base structure, and then you can add additional visual properties (e.g., positions of text, colors, plot theme, etc.).

In this post, I will show you how to use ggplot2 to generate an errorbar plot. The plot has side-by-side bar plots with an errorbar. I am using the mean for the bar plot and the 95% confidence interval to show the errorbar. To create a plot using ggplot, you need first to define a data frame. The data frame should contain all the columns you will use in the ggplot (e.g., values for the x-axis, values for the y-axis, etc.).

Generate random data and compute the mean and standard error for the data:


# generate random float values
a1 <- runif(200)
a2 <- runif(200)
a3 <- runif(200)
a4 <- runif(200)
a5 <- runif(200)

b1 <- runif(200)
b2 <- runif(200)
b3 <- runif(200)
b4 <- runif(200)
b5 <- runif(200)

# mean vector
mean_vec_a <- c(mean(a1), mean(a2), mean(a3), mean(a4), mean(a5))
mean_vec_b <- c(mean(b1), mean(b2), mean(b3), mean(b4), mean(b5))

# standard error vector
se_vec_a <- c(std.error(a1), std.error(a2), std.error(a3), std.error(a4), std.error(a5))
se_vec_b <- c(std.error(b1), std.error(b2), std.error(b3), std.error(b4), std.error(b5))

Generate data frame for ggplot using the mean vector and standard error vector:

# x-axis values and data frame for ggplot.
# number of elements in each of the data frame columns should be same. 
x_vals <- c("1", "2", "3", "4", "5")
df <- data.frame(
  xv=c(x_vals, x_vals),
  yv=c(mean_vec_a, mean_vec_b),
  sev=c(se_vec_a, se_vec_b),
  Vectors=c(rep("a", length(x_vals)), rep("b", length(x_vals)))

Generate plot using ggplot:

# prepare ggplot plot
p <- ggplot(data = df, aes(x=xv, y=yv, fill=Vectors)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin=yv-(1.96*sev), ymax=yv+(1.96*sev)), width=0.1, position=position_dodge(0.8)) +
  theme_bw() +
  scale_y_continuous(breaks = seq(0, 1.0, 0.02), expand = expansion(mult=c(0,0), add = c(0,0.05))) +
  labs(x = "X label", y = "Y label", title="Errorbar plot") +
  scale_fill_manual(values=c('brown1', 'dodgerblue'))


You can combine the three sections to get the complete code. Also, you can replace the randomly generated data (a1…a5, b1…b5) with your real data to generate the plot.

The above code will generate the following error plot with the errorbar.

Please let me know in the comment if you get any errors in the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.