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.
Modifying text
To clean this figure up for a publication we need to change some of the text elements. The x-axis is too cluttered, and the y axis should read "Life expectancy", rather than the column name in the data frame.
We can do this by adding a couple of different layers. The theme layer
controls the axis text, and overall text size. Labels for the axes, plot
title and any legend can be set using the labs
function. Legend titles
are set using the same names we used in the aes
specification. Thus below
the color legend title is set using color = "Continent"
, while the title
of a fill legend would be set using fill = "MyTitle"
.
ggplot(data = americas, mapping = aes(x = year, y = lifeExp, color=continent)) + geom_line() + facet_wrap( ~ country) + labs( x = "Year", # x axis title y = "Life expectancy", # y axis title title = "Figure 1", # main title of figure color = "Continent" # title of legend ) + theme(axis.text.x = element_text(angle = 90, hjust = 1))