...

/

Aesthetics in the ggplot2 Package

Aesthetics in the ggplot2 Package

Explore the role of aesthetics—an element of the grammar of graphics.

Plot layers in ggplot2

Any plot in the ggplot2 package is created using the ggplot() function. It must have the following three components (layers) as specified by the layered grammar of graphics:

1. Data: The data to be used should be present in a data frame.

2. Aesthetics: These are represented by the aes() function, which is responsible for positioning/mapping the variables on the plot.

3. Geometry: The geom function directs the plot on how to present the data in R. For example, we will use the geom_line() function to create a line chart. Many predefined geom functions are available to make different types of plots.

In simple words, these three components can be seen as layers that, added on top of each other, will form the resulting plot. The following syntax is used to create all types of plots in the ggplot2 package:

Press + to interact
Structure of ggplot syntax
Structure of ggplot syntax

Where X and Y are variables in a dataset.

The + sign is used to add layers and must appear at the end of each line that contains a layer. If the + sign is not placed correctly, the new layer will not be added by ggplot2, and an error notice will be displayed.

Press + to interact
Error message on putting + sign on a new line
Error message on putting + sign on a new line

Below is an example of incorrect syntax. Note the placement of the + sign in the code. It is incorrect as it is placed on a new line.

Press + to interact
ggplot(data = dataframe)
+ geom_point(aes(x = X, y = Y))

Below is an example of the correct syntax for adding a new layer:

Press + to interact
ggplot(data = dataframe)+
geom_point(aes(x = X, y = Y))

It is important to remember that ggplot2 expects a data frame for the data layer. The ggplot2 and ggplot functions are often used interchangeably in different articles, but ggplot2 refers to the most recent version of the software. However, the function is always invoked using the ggplot() function.

Only using the ggplot(data=dataframe) command will add the data ...