Learn R · 9/15

Data Visualization with ggplot2

9 min read

Data Visualization with ggplot2 🎨

Welcome to the wonderful world of data visualization with ggplot2! If you've ever stared at a spreadsheet full of numbers and wished you could just see what it all means, you're in the right place. ggplot2 is a powerful and popular R package that helps you create beautiful and informative graphics.

The Problem: Raw data, in its tabular form, is often difficult to interpret. It's hard to spot trends, outliers, or relationships just by looking at rows and columns.

The Solution: ggplot2 allows you to translate that data into visual representations, making it much easier to understand and communicate your findings. Think of it as telling a story with your data.

Before we dive in, let's get you set up.

Getting Started: Installation and Setup

To begin our journey, you'll need to have ggplot2 installed and loaded in your R environment. It's as simple as a couple of lines of code.

r
# If you don't have ggplot2 installed, run this line first:
install.packages("ggplot2")

# Load the ggplot2 library to start using its functions
library(ggplot2)

With that, you're ready to start creating some amazing plots!

The Grammar of Graphics: Understanding the ggplot Canvas

At the heart of ggplot2 is the "Grammar of Graphics," a concept that breaks down a plot into its fundamental components. Don't let the term "grammar" scare you; it's just a systematic way of thinking about how to build a plot.

Imagine you're an artist about to paint. What's the very first thing you need? A canvas! In ggplot2, the ggplot() function creates that canvas for you.

The Problem: Before you can draw anything, you need a space to draw on and a subject to draw. In data visualization, this means you need a plotting area and you need to tell your plotting tool what data you're going to use.

The Solution: The ggplot() function initializes a plot object. It's where you'll specify the dataset you want to visualize.

Here's the basic structure:

r
ggplot(data = your_dataset)

This line of code creates an empty plot. It doesn't look like much yet, but it's the foundation upon which we'll build everything else.

An Interesting Fact: The "gg" in ggplot2 stands for "Grammar of Graphics". This framework was developed by Leland Wilkinson and later adapted and popularized by Hadley Wickham, the creator of ggplot2.

Basic Geometries: Scatter Plots, Lines, and Bars

Now that we have our canvas, it's time to add some "geoms." Geoms are the geometric objects that represent your data. Think of them as the different types of brushes and pens you can use to draw on your canvas. The most common ones you'll use are points, lines, and bars.

Scatter Plots with geom_point()

The Problem: You have two continuous variables and you want to see if there's a relationship between them. For instance, is there a connection between a car's engine size and its fuel efficiency?

The Solution: A scatter plot is perfect for this. It uses points to show the relationship between two numeric variables. In ggplot2, you create a scatter plot using geom_point().

Let's use the built-in mtcars dataset to explore the relationship between engine displacement (disp) and miles per gallon (mpg).

r
# Create a scatter plot of engine displacement vs. mpg
ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point()

Notice the aes() function inside ggplot(). We'll cover that in more detail in the next section, but for now, just know that it's where you define the "aesthetic mappings" – how variables in your data are mapped to visual properties of the plot. Here, we're mapping disp to the x-axis and mpg to the y-axis.

Line Plots with geom_line()

The Problem: You have data that changes over time, and you want to visualize the trend. For example, how has the population of a city grown over the last few decades?

The Solution: A line plot is ideal for showing trends over a continuous variable, often time. You use geom_line() to create these.

Let's imagine we have a dataset of a plant's growth over several days.

r
# Create a sample dataset
plant_growth <- data.frame(
  day = 1:10,
  height = c(2, 4, 7, 11, 15, 18, 21, 23, 24, 25)
)

# Create a line plot of the plant's growth
ggplot(data = plant_growth, aes(x = day, y = height)) +
  geom_line()

Bar Charts with geom_bar() and geom_col()

The Problem: You want to compare a numerical value across different categories. For example, which car manufacturer produces the most models in our dataset?

The Solution: Bar charts are excellent for comparing quantities across different groups. ggplot2 offers two main functions for this:

  • geom_bar(): Makes the height of the bar proportional to the number of cases in each group.
  • geom_col(): Use this when you have a column in your data that already represents the bar height.

Let's see how many cars of each cylinder type are in the mtcars dataset.

r
# Create a bar chart showing the count of cars for each cylinder type
ggplot(data = mtcars, aes(x = factor(cyl))) +
  geom_bar()

Mapping Aesthetics: Colors, Shapes, and Sizes 🎨

Now for the fun part: making our plots more informative and visually appealing! Aesthetics are the visual properties of the geoms, like color, shape, and size.

The Problem: A basic plot shows the relationship between two variables. But what if you want to incorporate a third variable into the visualization?

The Solution: You can map other variables in your data to aesthetics. This is done inside the aes() function. This allows you to encode more information into a single plot.

Let's go back to our mtcars scatter plot and add information about the number of cylinders (cyl).

Mapping Color

We can use color to represent the number of cylinders.

r
# Map the number of cylinders to the color of the points
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point()

Now, points for cars with different numbers of cylinders will have different colors.

Mapping Shape

We can also map the number of cylinders to the shape of the points.

r
# Map the number of cylinders to the shape of the points
ggplot(data = mtcars, aes(x = disp, y = mpg, shape = factor(cyl))) +
  geom_point()

You'll see different shapes for 4, 6, and 8-cylinder cars.

Mapping Size

Let's try mapping the car's weight (wt) to the size of the points.

r
# Map the car's weight to the size of the points
ggplot(data = mtcars, aes(x = disp, y = mpg, size = wt)) +
  geom_point()

Heavier cars will now have larger points.

You can even combine these!

r
# Map cylinders to color and weight to size
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl), size = wt)) +
  geom_point()

Customization: Themes, Labels, and Legends 🖌️

While ggplot2's default plots are quite good, you'll often want to customize them to make them clearer and more professional.

The Problem: The default titles, labels, and overall look of a plot might not be suitable for a presentation or report. You need to be able to change these elements.

The Solution: ggplot2 provides a powerful set of functions to customize almost every aspect of your plot.

Adding Labels and Titles with labs()

You can easily change the title, subtitle, caption, and axis labels using the labs() function.

r
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(
    title = "Fuel Efficiency vs. Engine Displacement",
    subtitle = "Data from 1974 Motor Trend US magazine",
    x = "Engine Displacement (cubic inches)",
    y = "Miles Per Gallon",
    color = "Number of Cylinders",
    caption = "Source: mtcars dataset"
  )

Customizing the Overall Look with theme()

The theme() function gives you control over the non-data elements of the plot, like the background, gridlines, and fonts. There are also several built-in themes you can apply for a quick makeover.

r
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(
    title = "Fuel Efficiency vs. Engine Displacement",
    x = "Engine Displacement (cubic inches)",
    y = "Miles Per Gallon",
    color = "Number of Cylinders"
  ) +
  theme_minimal() # Try theme_bw(), theme_classic(), etc.

For more detailed customization, you can modify specific theme elements.

r
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(
    title = "Fuel Efficiency vs. Engine Displacement",
    x = "Engine Displacement (cubic inches)",
    y = "Miles Per Gallon",
    color = "Number of Cylinders"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
    axis.title = element_text(size = 12)
  )

Modifying the Legend

The legend is automatically generated, but you have control over its appearance and position.

r
ggplot(data = mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(
    title = "Fuel Efficiency vs. Engine Displacement",
    x = "Engine Displacement (cubic inches)",
    y = "Miles Per Gallon",
    color = "Cylinders"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom") # Try "top", "left", "right", or "none"

Faceting: Creating Multi-Panel Plot Grids 🖼️

Faceting is a powerful technique for creating multiple plots that show different subsets of your data. This is also known as creating "small multiples."

The Problem: You have a categorical variable with several levels, and you want to see the relationship between two other variables for each of those levels. Creating a separate plot for each level would be tedious.

The Solution: ggplot2 provides two main functions for faceting:

  • facet_wrap(): Creates a "ribbon" of plots and wraps them into a 2D grid.
  • facet_grid(): Creates a grid of plots defined by one or two variables.

facet_wrap()

Let's say we want to see the relationship between displacement and mpg for each cylinder type separately.

r
ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_wrap(~ factor(cyl)) +
  labs(title = "Fuel Efficiency vs. Displacement by Number of Cylinders")

This will create three separate plots, one for each cylinder type, arranged in a grid.

facet_grid()

facet_grid() is useful when you want to facet by two variables, creating a grid where the rows represent one variable and the columns represent another.

Let's look at the relationship between displacement and mpg, faceted by both the number of cylinders (cyl) and the type of transmission (am, where 0 = automatic, 1 = manual).

r
ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_grid(am ~ cyl) +
  labs(title = "Fuel Efficiency vs. Displacement by Transmission and Cylinders")

This creates a grid of plots where the rows correspond to the transmission type and the columns to the number of cylinders.


Further Reading and Resources 📚

To continue your ggplot2 journey, here are some excellent resources:

Challenge

Task

Using the built-in mtcars dataset in R, construct a single ggplot2 visualization that explores the relationship between vehicle weight, fuel efficiency, horsepower, and cylinder count, faceted by the number of gears.

Requirements

  1. Initialize your plot using the mtcars dataset.
  2. Create a scatter plot using geom_point().
  3. Map the aesthetics (aes) as follows:
    • wt (Weight) should be on the x-axis.
    • mpg (Miles Per Gallon) should be on the y-axis.
    • cyl (Number of cylinders) should determine the color of the points. Ensure cyl is treated as a categorical variable.
    • hp (Gross horsepower) should determine the size of the points.
  4. Create separate plot panels for each unique value in the gear (Number of forward gears) column using faceting.
  5. Apply the theme_minimal() to the plot for a clean appearance.
  6. Add the following labels using the labs() function:
    • Title: "Fuel Efficiency vs. Weight, Colored by Cylinders"
    • Subtitle: "Faceted by the Number of Forward Gears"
    • x-axis label: "Weight (1000 lbs)"
    • y-axis label: "Miles Per Gallon"
    • Caption: "Data source: mtcars dataset"
    • Color Legend Title: "Cylinders"
    • Size Legend Title: "Horsepower"

Expected result

Your R code should create a ggplot object that chains together several layers to produce the required visualization. The final code should look similar to this structure:

r
library(ggplot2)

ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = factor(cyl), size = hp)) +
  facet_wrap(~ gear) +
  theme_minimal() +
  labs(
    title = "Fuel Efficiency vs. Weight, Colored by Cylinders",
    subtitle = "Faceted by the Number of Forward Gears",
    x = "Weight (1000 lbs)",
    y = "Miles Per Gallon",
    caption = "Data source: mtcars dataset",
    color = "Cylinders",
    size = "Horsepower"
  )

Breakdown of the correct solution:

  • ggplot(data = mtcars, aes(x = wt, y = mpg)): This initializes the plot, specifying the mtcars dataset and the primary aesthetic mappings for the x and y axes.
  • geom_point(aes(color = factor(cyl), size = hp)): This adds the scatter plot layer. Crucially, it maps color to factor(cyl) to ensure ggplot treats the number of cylinders as distinct categories rather than a continuous number. It also maps size to hp.
  • facet_wrap(~ gear): This function creates the separate panels for each gear count.
  • theme_minimal(): This applies the specified clean theme.
  • labs(...): This function sets all the required text elements, including the main title, subtitle, axis labels, caption, and the titles for the color and size legends.
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.