Get startedGet started for free

ggplot2 layers

1. ggplot2 layers

Now that we have some idea about the different grammatical elements of graphics, let's see how this works in practice.

2. ggplot2 package

The grammar of graphic is implemented in R using the ggplot2 package. There are two key functions that ggplot2 serves. First, we construct plots by layering grammatical elements on top of each other. Second, we use aesthetic mappings to bridge the link between data and it's visual interpretation. We are going to go through each grammatical element in depth in this and the next course. Here I'll introduce a data set which will be used throughout the videos and we'll go over some simple examples.

3. Data

The bottom layer is the data element. Obviously we need some data to plot. I'm going to use several different data sets in the course videos,

4. Iris dataset

one of which is the classic iris data set collected by Edgar Anderson in the 1930s and thereafter popularized by Ronald Fisher. The data set contains information on three iris species, setosa, versicolor, and virginica. Four measurements were taken from each plant - the petal length and width and the sepal length and width. You're probably familiar with petals, they're the colorful part of a flower. Sepals are the outer leaves of the flower, they are typically green, but in this case they're also colorful. There are 50 specimens of each species.

5. Iris dataset

The data is stored in an object called iris, there are five variables: the species and one for each of the properties which were measured.

6. Aesthetics

The next layer we'll add is the aesthetics element, which tells us which scales we should map our data onto. This is where the second main component of the grammar of graphics comes into play. On top of layering the grammatical elements, it's here that we establish our aesthetic mappings.

7. Iris aesthetics

In this case we are going to make a scatter plot so we're going to map Sepal-dot-Length onto the X aesthetic and Sepal-dot-Width onto the Y aesthetic.

8. Geometries

The next element is the geometry element. This allows us to choose how the plot will look.

9. Iris geometries

After we've established our three essential layers, we have enough instructions to make a basic scatter plot. It's pretty rough, so to get a more meaningful and cleaner visualization, we'll have to use the other layers.

10. Themes

The next layer we'll look at is the themes element. It controls all the non-data ink on our plot.

11. Iris themes

Which allows us to get a nice looking, meaningful and publication-quality plot directly in R.

12. Let's practice!

We'll discuss the remaining grammatical elements in the next course. For now, let's begin by exploring these concepts in the exercises.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.