geom_bar
This post
describes how to build a barplot with R, using the
geom_bar()
function.
geom_bar()
This is the most basic barplot you can build using the
ggplot2
package. It follows those steps:
ggplot()
function.data
object. It has to be a data
frame.aes()
function:
set the categoric variable for the X axis, use the numeric for the Y
axisgeom_bar()
. You have to specify
stat="identity"
for this kind of dataset.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")
.
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.
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.
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.