Introduction to ggplot
This section introduces the ggplot2
graphics. You will see how different the syntax is from the base-R graphics. You can think of ggplot2
creating graphs by combining layers with the "+" sign. The default gray background of the ggplot
is not as good for printed publications and can be replaced by adding a theme layer, for example, + theme_minimal()
Key Points
-
Use
ggplot2
to create plots. -
Think about graphics in layers: aesthetics, geometry, statistics, scale transformation, and grouping.
Multi-panel figures
Earlier we visualized the change in life expectancy over time across all countries in one plot. Alternatively, we can split this out over multiple panels by adding a layer of facet panels.
Tip
We start by making a subset of data including only countries located in the Americas. This includes 25 countries, which will begin to clutter the figure. Note that we apply a "theme" definition to rotate the x-axis labels to maintain readability. Nearly everything in ggplot2 is customizable.
americas <- gapminder[gapminder$continent == "Americas",] ggplot(data = americas, mapping = aes(x = year, y = lifeExp)) + geom_line() + facet_wrap( ~ country) + theme(axis.text.x = element_text(angle = 45))
The facet_wrap
layer took a "formula" as its argument, denoted by the tilde
(~). This tells R to draw a panel for each unique value in the country column
of the gapminder dataset.