Creating aesthetic mappings
library(ggplot2)
ggplot(___) +
geom_point(
mapping = aes(x = ___, y = ___)
)
View Interactive Versionggplot2 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:
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:
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:
- Load the package ggplot2 using
library(ggplot2)
. - Specify the dataset to be plotted using
ggplot()
. - Use the
+
operator to add layers to the plot. - Add a geometric layer to define the shapes to be plotted. In case of scatter plots, use
geom_point()
. - Map variables from the dataset to plotting properties through the
mapping
parameter in the geometric layer.