Creating aesthetic mappings

library(ggplot2)
ggplot(___) + 
  geom_point(
    mapping = aes(x = ___, y = ___)
  )
View Interactive Version

ggplot2 uses the concept of aesthetics, which map dataset attributes to the visual features of the plot. Each geometric layer requires a different set of aesthetic mappings, e.g. the geom_point() function uses the aesthetics x and y to determine the x- and y-axis coordinates of the points to plot. The aesthetics are mapped within the aes() function to construct the final mappings.

To specify a layer of points which plots the variable speed on the x-axis and distance dist on the y-axis we can write:

Input
geom_point(
  mapping = aes(x=speed, y=dist)
)

The expression above constructs a geometric layer. However, this layer is currently not linked to a dataset and does not produce a plot. To link the layer with a ggplot object specifying the cars dataset we need to connect the ggplot(cars) object with the geom_point() layer using the + operator:

Input
ggplot(cars) + 
  geom_point(
    mapping = aes(x=speed, y=dist)
  )

Through the linking ggplot() knows that the mapped speed and dist variables are taken from the cars dataset. geom_point() instructs ggplot to plot the mapped variables as points.

The required steps to create a scatter plot with ggplot can be summarized as follows:

  1. Load the package ggplot2 using library(ggplot2).
  2. Specify the dataset to be plotted using ggplot().
  3. Use the + operator to add layers to the plot.
  4. Add a geometric layer to define the shapes to be plotted. In case of scatter plots, use geom_point().
  5. Map variables from the dataset to plotting properties through the mapping parameter in the geometric layer.
Create a scatter plot with ggplot