Barplot with geom_bar


This post describes how to build a barplot with R, using the geom_bar() function.

Basic barplot with geom_bar()


This is the most basic barplot you can build using the ggplot2 package. It follows those steps:

  • always start by calling the ggplot() function.
  • then specify the data object. It has to be a data frame.
  • then come the aesthetics, set in the aes() function: set the categoric variable for the X axis, use the numeric for the Y axis
  • finally call geom_bar(). You have to specify stat="identity" for this kind of dataset.

Control bar color


Here are a few different methods to control bar colors. Note that using a legend in this case is not necessary since names are already displayed on the X axis. You can remove it with theme(legend.position="none").

Horizontal barplot with coord_flip()


It often makes sense to turn your barplot horizontal. Indeed, it makes the group labels much easier to read.

Fortunately, the coord_flip() function makes it a breeze.

Control bar width with width


The width argument of the geom_bar() function allows to control the bar width. It ranges between 0 and 1, 1 being full width.




Contact

This document is a work of the statistics team in the Biostatistics and Medical Information Department at Saint-Louis Hospital in Paris (SBIM).
Based on The R Graph Gallery by Yan Holtz.

SBIM