Hands-on Exercise 1

Author

Yee Weicong Mark

Published

April 10, 2026

Modified

May 16, 2026

Basic Principles and Essential Components of ggplot2

This page introduces the Layered Grammar of Graphics and demonstrates how ggplot2 implements it through its essential components.

1. Installing and loading the required libraries

Load the required packages:

pacman::p_load(tidyverse)

2. Importing Data

  • The code chunk below imports exam_data.csv into R environment by using read_csv() function of readr package.

  • readr is one of the tidyverse package.

exam_data <- read_csv("data/Exam_data.csv")

3. R Graphics VS ggplot

Let us compare how R Graphics, the core graphical functions of Base R and ggplot plot a simple histogram.

hist(exam_data$MATHS)

ggplot(data=exam_data, aes(x = MATHS)) +
  geom_histogram(bins=10, 
                 boundary = 100,
                 color="black", 
                 fill="grey") +
  ggtitle("Distribution of Maths scores")

The code chunk is relatively simple if R Graphics is used. Then, the question is why ggplot2 is recommended?

4. Essential Grammatical Elements in ggplot2: data

ggplot(data=exam_data)

  • A blank canvas appears.

  • ggplot() initializes a ggplot object.

  • The data argument defines the dataset to be used for plotting.

  • If the dataset is not already a data.frame, it will be converted to one by fortify().

5. Essential Grammatical Elements in ggplot2: Aesthetic mappings

The aesthetic mappings take attributes of the data and and use them to influence visual characteristics, such as position, colour, size, shape, or transparency. Each visual characteristic can thus encode an aspect of the data and be used to convey information.

All aesthetics of a plot are specified in the aes() function call (in later part of this lesson, you will see that each geom layer can have its own aes specification)

Code chunk below adds the aesthetic element into the plot.

ggplot(data=exam_data, 
       aes(x= MATHS))

6. Essential Grammatical Elements in ggplot2: geom

Geometric objects are the actual marks we put on a plot. Examples include:

  • geom_point for drawing individual points (e.g., a scatter plot)

  • geom_line for drawing lines (e.g., for a line charts)

  • geom_smooth for drawing smoothed lines (e.g., for simple trends or approximations)

  • geom_bar for drawing bars (e.g., for bar charts)

  • geom_histogram for drawing binned values (e.g. a histogram)

  • geom_polygon for drawing arbitrary shapes

  • geom_map for drawing polygons in the shape of a map! (You can access the data to use for these maps by using the map_data() function).

  • A plot must have at least one geom; there is no upper limit. You can add a geom to a plot using the + operator.

  • For complete list, please refer to here.

6.1 Geometric Objects: geom_bar()

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar()

6.2 Geometric Objects: geom_dotplot()

In a dot plot, the width of a dot corresponds to the bin width (or maximum width, depending on the binning algorithm), and dots are stacked, with each dot representing one observation.

ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot(dotsize = 0.5)

ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot(binwidth=2.5,         
               dotsize = 0.5) +      
  scale_y_continuous(NULL,           
                     breaks = NULL)  

6.3 Geometric Objects: geom_histogram()

ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_histogram()       

6.4 Modifying a Geometric Object by Changing geom()

In the code chunk below,

  • bins argument is used to change the number of bins to 20,

  • fill argument is used to shade the histogram with light blue color, and

  • color argument is used to change the outline colour of the bars in black

ggplot(data=exam_data, 
       aes(x= MATHS)) +
  geom_histogram(bins=20,            
                 color="black",      
                 fill="light blue")  

6.5 Modifying a Geometric Object by Changing aes()

The code chunk below changes the interior colour of the histogram (i.e. fill) by using sub-group of aesthetic().

ggplot(data=exam_data, 
       aes(x= MATHS, 
           fill = GENDER)) +
  geom_histogram(bins=20, 
                 color="grey30")

6.6 Geometric Objects: geom_density()

geom-density() computes and plots kernel density estimate, which is a smoothed version of the histogram.

It is a useful alternative to the histogram for continuous data that comes from an underlying smooth distribution.

The code below plots the distribution of Maths scores in a kernel density estimate plot.

ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_density()           

The code chunk below plots two kernel density lines by using colour or fill arguments of aes()

ggplot(data=exam_data, 
       aes(x = MATHS, 
           colour = GENDER)) +
  geom_density()

6.7 Geometric Objects: geom_boxplot()

geom_boxplot() displays continuous value list. It visualises five summary statistics (the median, two hinges and two whiskers), and all “outlying” points individually.

The code chunk below plots boxplots by using geom_boxplot().

ggplot(data=exam_data, 
       aes(y = MATHS,       
           x= GENDER)) +    
  geom_boxplot()            

Notches are used in box plots to help visually assess whether the medians of distributions differ. If the notches do not overlap, this is evidence that the medians are different.

The code chunk below plots the distribution of Maths scores by gender in notched plot instead of boxplot.

ggplot(data=exam_data, 
       aes(y = MATHS, 
           x= GENDER)) +
  geom_boxplot(notch=TRUE)

6.8 Geometric Objects: geom_violin()

geom_violin is designed for creating violin plot. Violin plots are a way of comparing multiple data distributions. With ordinary density curves, it is difficult to compare more than just a few distributions because the lines visually interfere with each other. With a violin plot, it’s easier to compare several distributions since they’re placed side by side.

The code below plot the distribution of Maths score by gender in violin plot.

ggplot(data=exam_data, 
       aes(y = MATHS, 
           x= GENDER)) +
  geom_violin()

6.9 Geometric Objects: geom_point()

geom_point() is especially useful for creating scatterplot.

The code chunk below plots a scatterplot showing the Maths and English grades of pupils by using geom_point().

ggplot(data=exam_data, 
       aes(x= MATHS, 
           y=ENGLISH)) +
  geom_point()            

6.10 geom Objects can be Combined

geom_point() is especially useful for creating scatterplot.

The code chunk below plots the data points on the boxplots by using both geom_boxplot() and geom_point().

ggplot(data=exam_data, 
       aes(y = MATHS, 
           x= GENDER)) +
  geom_boxplot() +                    
  geom_point(position="jitter", 
             size = 0.5)        

7. Essential Grammatical Elements in ggplot2: stat

The Statistics functions statistically transform data, usually as some form of summary. For example:

  • frequency of values of a variable (bar graph)

    • a mean

    • a confidence limit

  • There are two ways to use these functions:

    • add a stat_() function and override the default geom, or

    • add a geom_() function and override the default stat.

7.1 Working with stat()

The boxplots below are incomplete because the positions of the means were not shown.

ggplot(data=exam_data, 
       aes(y = MATHS, x= GENDER)) +
  geom_boxplot()

7.2 Working with stat - the stat_summary() method

The code chunk below adds mean values by using stat_summary() function and overriding the default geom.

ggplot(data=exam_data, 
       aes(y = MATHS, x= GENDER)) +
  geom_boxplot() +
  stat_summary(geom = "point",       
               fun = "mean",         
               colour ="red",        
               size=4)               

7.3 Working with stat - the geom() method

The code chunk below adding mean values by using geom_() function and overriding the default stat.

ggplot(data=exam_data, 
       aes(y = MATHS, x= GENDER)) +
  geom_boxplot() +
  geom_point(stat="summary",        
             fun="mean",           
             colour="red",          
             size=4)          

7.4 Adding a Best Fit Curve on a Scatterplot

The scatterplot below shows the relationship of Maths and English grades of pupils. The interpretability of this graph can be improved by adding a best fit curve.

In the code chunk below, geom_smooth() is used to plot a best fit curve on the scatterplot.

ggplot(data=exam_data, 
       aes(x= MATHS, y=ENGLISH)) +
  geom_point() +
  geom_smooth(size=0.5)

The default smoothing method can be overridden as shown below.

ggplot(data=exam_data, 
       aes(x= MATHS, 
           y=ENGLISH)) +
  geom_point() +
  geom_smooth(method=lm, 
              linewidth=0.5)

8. Essential Grammatical Elements in ggplot2: Facets

Facetting generates small multiples (sometimes also called trellis plot), each displaying a different subset of the data. They are an alternative to aesthetics for displaying additional discrete variables. ggplot2 supports two types of factes, namely: facet_grid() and facet_wrap.

8.1 Working with facet_wrap()

facet_wrap wraps a 1d sequence of panels into 2d. This is generally a better use of screen space than facet_grid because most displays are roughly rectangular.

The code chunk below plots a trellis plot using facet-wrap().

ggplot(data=exam_data, 
       aes(x= MATHS)) +
  geom_histogram(bins=20) +
    facet_wrap(~ CLASS)

8.2 facet_grid() Function

facet_grid() forms a matrix of panels defined by row and column facetting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

The code chunk below plots a trellis plot using facet_grid().

ggplot(data=exam_data, 
       aes(x= MATHS)) +
  geom_histogram(bins=20) +
    facet_grid(~ CLASS)

9. Essential Grammatical Elements in ggplot2: Coordinates

The Coordinates functions map the position of objects onto the plane of the plot. There are a number of different possible coordinate systems to use, they are:

  • coord_cartesian(): the default cartesian coordinate systems, where you specify x and y values (e.g. allows you to zoom in or out).
  • coord_flip(): a cartesian system with the x and y flipped.
  • coord_fixed(): a cartesian system with a “fixed” aspect ratio (e.g. 1.78 for a “widescreen” plot).
  • coord_quickmap(): a coordinate system that approximates a good aspect ratio for maps.

9.1 Working with Coordinate

By the default, the bar chart of ggplot2 is in vertical form.

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar()

The code chunk below flips the horizontal bar chart into vertical bar chart by using coord_flip().

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar() +
  coord_flip()

9.2 Changing the y- and x-axis Range

The scatterplot on the right is slightly misleading because the y-aixs and x-axis range are not equal.

ggplot(data=exam_data, 
       aes(x= MATHS, y=ENGLISH)) +
  geom_point() +
  geom_smooth(method=lm, size=0.5)

The code chunk below fixed both the y-axis and x-axis range from 0-100.

ggplot(data=exam_data, 
       aes(x= MATHS, y=ENGLISH)) +
  geom_point() +
  geom_smooth(method=lm, 
              size=0.5) +  
  coord_cartesian(xlim=c(0,100),
                  ylim=c(0,100))

10. Essential Grammatical Elements in ggplot2: themes

Themes control elements of the graph not related to the data. For example:

  • background colour

  • size of fonts

  • gridlines

  • colour of labels

Built-in themes include: - theme_gray() (default) - theme_bw() - theme_classic()

A list of theme can be found at this link. Each theme element can be conceived of as either a line (e.g. x-axis), a rectangle (e.g. graph background), or text (e.g. axis title).

10.1 Working with theme

The code chunk below plot a horizontal bar chart using theme_gray().

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar() +
  coord_flip() +
  theme_gray()

A horizontal bar chart plotted using theme_classic().

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar() +
  coord_flip() +
  theme_classic()

A horizontal bar chart plotted using theme_minimal().

ggplot(data=exam_data, 
       aes(x=RACE)) +
  geom_bar() +
  coord_flip() +
  theme_minimal()

:::


🕹️ LEVEL COMPLETE 🕹️

★ ★ ★ ★ ★

HANDS-ON EXERCISE 1 CLEARED!

+500 XP · ACHIEVEMENT UNLOCKED: Grammar of Graphics Apprentice 📊

Press any key to continue…