View Interactive Version
library(ggplot2) ggplot(___) + geom_point( mapping = aes(x = ___, y = ___) )
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
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
ggplot(cars) + geom_point( mapping = aes(x=speed, y=dist) )
Through the linking
ggplot() knows that the mapped
dist variables are taken from the
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:
+operator to add layers to the plot.
mappingparameter in the geometric layer.