Using Facets to Split Data

In this section, we'll plot subsets of data as separate subplots. Let's begin by implementing the following steps:

  1. Use the gapminder.csv dataset.
  2. Make a scatter plot of Electricity_consumption_per_capita versus gdp_per_capita:
p <- ggplot (df, aes (x=gdp_per_capita, y=Electricity_consumption_per_capita)) + geom_point ()
  1. Use facet_grid() to specify the variables to split upon. We will need to plot the electricity consumption versus GDP separately for each country. So, our split variable will be Country:
p + facet_grid(Country ~ .) 

Take a look at the following output scatter plot:

  1. You can also arrange the panels ...

Get Applied Data Visualization with R and ggplot2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.