Basic Plots in ggplot2
Learn to create plots and plot templates using ggplot2.
We'll cover the following
Similar to the tidyverse,
calls to ggplot2
are based on an underlying structure. Once we’re comfortable with that basic structure, we’ll find that we can efficiently construct most graphs with only minor modifications to our code. The base structure for creating a plot in ggplot2
is:
DATA %>% ggplot(mapping = aes(mappings)) + geom_function() + labs()
So, to map that back to the grammar of graphics, we’re specifying:
-
DATA
: This is the tidy data that we want to visualize. -
aes(mappings)
: This is the aesthetics that will describe our plot, i.e., the specifications about how the data points will be visually represented. For most fundamental plots, this will map variables to elements of the visualization, i.e., determining which variable goes on the x-axis and which variable goes on the y-axis. -
geom_function
: This is a function specifying how our data will be represented, e.g., by points (as in a scatter plot), a smooth curve or a line (as in a scatter plot with a trend line), or a histogram to show the distribution of a single variable. -
labs()
: This is where we’ll specify labels for our plots. For example, legends, main titles, and axes titles.
The one element we’re not specifying is the coordinate system. In most cases, the default coordinate system will work, so we won’t need to set this.
Get hands-on with 1400+ tech skills courses.