Bar Graphs (ggplot)


The mtcars data frame ships with R and was extracted from the 1974 US Magazine Motor Trend.  The data compares fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). 

Basic Bar Graph Syntax

A basic plot skeleton is created by declaring the data, aesthetic mappings.  The additional stat argument is set equal to “bin” (the default) to obtain counts of the data observations and “identity” and to plot observed values.


Bar Graph Aesthetics

Bar chart aesthetics define the x data used, bar width, bar fill color, bar line color, linetype, and size, alpha level (or transparency) and weight.

Plot45 Plot48

Bar Graphs of Values vs Counts

So far, all bar graphs depict observation counts, not values.  The argument stat = “identity” must appear in geom_bar() to plot values.  The following code calculates the mean quarter mile times as a function of the number of cylinders, and depicts the resulting values


Changing the Order of the Bars

Use of the factor() command and the levels argument to control the order of the bars.  For example:


Stacked Bar Charts

Plot53 Plot54Plot55Plot56

Eliminating Space Between the Bottom of the Bars and the Axis

The white space found at the bottom of the bars can be eliminated using the scale_y_continuous() command with the following argument:


An Example: Fully Loaded

A bar-chart in finished form is depicted below and followed by code.


Back | Next