This intro covers the charting package ggplot2.

The “base” charting functionality will not be covered because it's much more difficult to achieve good looking results quickly and I don't believe in that much effort for so little benefit!



ggplot2 is a plotting system for R, based on the grammar of graphics, which tries to take the good parts of base and lattice graphics and none of the bad parts. It takes care of many of the fiddly details that make plotting a hassle (like drawing legends) as well as providing a powerful model of graphics that makes it easy to produce complex multi-layered graphics.


Term Explanation Example(s)
plot A plot using the grammar of graphics ggplot()
aesthetics attributes of the chart colour, x, y
mapping relating a column in your data to an aesthetic
statistical transformation a translation of the raw data into a refined summary stat_density()
geometry the display of aesthetics geom_line(), geom_bar()
scale the range of values axes, legends
coordinate system how geometries get laid out coord_flip()
facet a means of subsetting the chart facet_grid()
theme display properties theme_minimal()

Constructing a chart - a step by step process

  1. Create the base plot (doesn't work on it's own)

p <- ggplot(data=iris)
  1. Add aesthetic mappings (doesn't work on it's own)
p <- ggplot(data=iris, aes(x=Sepal.Width, y=Sepal.Length, colour=Species))
  1. Add a geometry
p <- p + geom_point()

plot of chunk unnamed-chunk-3

  1. (Optional) Add a statistic
p <- p + stat_boxplot(fill="transparent")
## Warning: position_dodge requires non-overlapping x intervals

plot of chunk unnamed-chunk-4

  1. (Optional) Alter coordinate system
p <- p + coord_flip()
## Warning: position_dodge requires non-overlapping x intervals

plot of chunk unnamed-chunk-5

  1. (Optional) Facet the chart
p <- p + facet_grid(.~Species)

plot of chunk unnamed-chunk-6

  1. (Optional) Amend look and feel
p <- p + optiRum::theme_optimum()

plot of chunk unnamed-chunk-7

Constructing a chart - a one-step process

ggplot(data=iris, aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) + 
  geom_point() +
  stat_boxplot(fill="transparent") +
  # coord_flip() + # Commented out
  facet_grid(.~Species) +

plot of chunk unnamed-chunk-8

More resources