Adding more lines
View Interactive Version
ggplot(___) + geom_line( mapping = aes(x = ___, y = ___, group = ___, color = ___) )
So far we only focused on single lines, but what if we have multiple countries in the dataset and want to somehow differentiate them?
Line graphs are often extended and used for the comparison of two or more lines. Multiple line graphs show the absolute differences between observations but also how the specific trajectories relate to each other. For example, let’s answer the question: How has life expectancy changed in the countries Austria and Hungary over time?
We first filter the dataset for both countries of interest. Then, we set the variable
country as the
group argument for the aesthetic mapping. The group argument tells ggplot which observations belong together and should be connected through lines. By specifying the
country variable ggplot creates a separate line for each country. To make the lines easier to distinguish we also map
color to the
country so that each country line has a different color.
gapminder_comparison <- filter(gapminder, country %in% c("Austria", "Hungary")) ggplot(data = gapminder_comparison) + geom_line(mapping = aes(x = year, y = lifeExp, group = country, color = country) )
Note that ggplot also separates the lines correctly if only the
color mapping is specified (the
group parameter is implicitly set).