Completing Our First Plot
We can now complete our understanding of this code block we first saw in the Our First Plot lesson.
library(tidyverse)
data(iris)
ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, colour = Species)) +
geom_point()
We went through the first two lines in the
Libraries and Packages lesson.
And now, with our understanding of functions, from the previous lesson,
we can delve into the last line, which introduces the
ggplot
function.
In this line, we can identify three functions based on the
presence of open and close parentheses:
ggplot
, aes
, and
geom_point
. Let's go through these one-by-one.
ggplot
The ggplot
function, part of the tidyverse
package, is used for plotting. Its first argument expects a dataframe, and
in this case, we provide the iris dataframe. Here are three observations
from this dataset:
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
7 | 3.2 | 4.7 | 1.4 | versicolor |
6.3 | 3.3 | 6 | 2.5 | virginica |
aes
The second parameter in ggplot
is the aes
function. "aes" stands for aesthetic mapping, instructing
ggplot
which variables from the dataframe to plot and
on which axes. Writing x = Sepal.Length
and y = Petal.Length
directs ggplot
to
place the Sepal.Length data on the x-axis and the
Petal.Length data on the y-axis.
The third parameter within aes
is the
colour parameter. This optional parameter is used to
colour the points based on groups within the argument we pass to
it, in this case the Species variable. Adding colour
to a plot really makes it pop!
geom_point
Hidden from us within geom_point
is code that will know how to
take our arguments to produce a scatter plot with labelled axes and points
representing our data. There are more plots we will
explore in future lessons such as the line plot, bar plot,
and violin plot.
An interesting thing about geom_point
is that
it uses the +
(plus) operator to inherit the data and
aesthetic mapping from the ggplot
function. As such,
we can use it here without writing anything inside the parenthesis.
This marks the final lesson in the Introduction section. In the next lesson we will transition to exploring fundamental concepts of R and broader computer science. But before we move on, let's admire that beautiful plot once more!