Step by step implementation of Grammar of Graphics in R

In previous article we discussed about qplot() which is analogy of plot(). Here in this tutorial we will cover ggplot2().

Basic component of ggplot2:

  • A dataframe :- Stores all of the data that will be displayed on the plot
  • Aesthetic mappings :- How data are mapped to color,size, etc.
  • geom :- geometric objects like points, lines,shapes, etc.
  • Facets :- facets are for conditionals plot, so you gonna have multiple panels. Make sure the relationship of something, something as third variable change.
  • Stats :- Statistical transformations like binning, quantiles, smoothing, regression, like that.
  • Scales :- How the different variables are coded in terms of plots. e.g. binary variables that represents gender(male, female).
  • Co-ordinate System :- How certain numerical representation get translated on to a plot.

Building plots with ggplot2():

when building the plot with ggplot2(), the basic idea, if you are not gonna use the qplot(), you wanna build by piece by piece. You can think of “artist’s palette” model.
This is the similar to model “base” plotting system. Where you gonna start something, you gonna add piece by piece, unlike the lattice plotting system. Where you had have to whole plot is enhanced in a single. You can add things piece by piece in ggplot2() plotting system. If you want some change in next line, you can make changes in next line.
To the ideas that the plots are built up in layers:

  • The most fundamental letter is called the data.
  • Overlay a summary, like smoothing, regression line.

Let’s start to build plotting using ggplot2() piece by piece:

  • geom_point.
  • geom_smooth.
  • aesthetic.
  • facets_grid.
  • annotations.
  • labels.
  • customising geom_smooth.

Let’s use the in-build dataset to understand the features of ggplot2().
Building up in layers:

It will look like this

Adding geom_points layer

Here is the plot, how it look like after adding geom_point layer to the ggplot2()

Adding geom_smooth() layers:

The plot looks like after adding geom_smooth()

Adding another layer facet:

Here the plot for facets_grid

Adding Annotations:

  • there are different kinds of labels like: xlab(),ylab(),labs(),ggtitle()
  • geom() has options to modify
  • theme()

There are built in themes also there which we can use

  • theme_gray() #default theme
  • theme_bw() #more stark/plain

Let’s talk about the modifying some of the features of aesthetic. Some example, changing the colors of object points.

Here is the plot, how it looks like

Here is the plot

Modifying Label:

Here is the plot

Customising  the Smooth

Here is the plot, how it looks like

That’s it folks about ggplot2(), if something missse please mention in  comments or shoot an email at

You might also like More from author