Skip to content

R - Scatterplots

Scatterplots are essential for visualizing the relationship between two continuous variables. Each point on the plot represents an observation, positioned according to its values on the horizontal (x) and vertical (y) axes. While R’s base graphics (plot()) can create simple scatterplots, the modern, powerful, and recommended approach is to use the ggplot2 package.

ggplot2 is based on the “Grammar of Graphics,” a philosophy that allows you to build plots layer by layer. The key components are:

  • data: The dataset containing the variables to plot.
  • aesthetics (aes): How variables are mapped to visual properties like the x/y axes, color, size, or shape.
  • geoms: The geometric objects that represent the data, such as points (geom_point), lines (geom_line), or bars (geom_bar).

We will use the built-in mtcars dataset to explore the relationship between vehicle weight (wt) and fuel efficiency (mpg).

# Install ggplot2 (part of the tidyverse) if you haven't already
# install.packages("tidyverse")
library(ggplot2)
library(dplyr)
# Select the relevant columns for clarity
input_data <- mtcars %>% select(wt, mpg, cyl, gear)
print(head(input_data))

When we execute the above code, it produces the following result:

wt mpg cyl gear
Mazda RX4 2.620 21.0 6 4
Mazda RX4 Wag 2.875 21.0 6 4
Datsun 710 2.320 22.8 4 4
Hornet 4 Drive 3.215 21.4 6 3
Hornet Sportabout 3.440 18.7 8 3
Valiant 3.460 18.1 8 3

The script below creates a polished scatterplot. We can add layers to the plot using the + operator.

# Create the scatterplot object
scatterplot <- ggplot(data = input_data, aes(x = wt, y = mpg)) +
geom_point() + # Add the layer for points
labs( # Add informative labels
title = "Vehicle Weight vs. Fuel Efficiency (MPG)",
subtitle = "Heavier cars tend to have lower mileage",
x = "Weight (1000 lbs)",
y = "Miles Per Gallon"
) +
theme_minimal() # Apply a clean, modern theme
# Print the plot to the viewer
print(scatterplot)
# Save the plot to a file
# ggsave automatically saves the last plot displayed
ggsave("scatterplot.png", width = 8, height = 5)

This code generates a file named scatterplot.png containing a well-labeled and clear scatterplot. The plot is also displayed in the RStudio Plots pane.

The power of ggplot2 comes from its ability to map other variables to aesthetics. For example, we can map the cyl (number of cylinders) variable to the color aesthetic to see how it influences the relationship.

# Create an enhanced scatterplot
enhanced_plot <- ggplot(data = input_data, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3, alpha = 0.8) + # Make points larger and slightly transparent
geom_smooth(method = "lm", se = FALSE) + # Add a linear regression line for each group
labs(
title = "Vehicle Weight vs. Fuel Efficiency by Cylinder Count",
x = "Weight (1000 lbs)",
y = "Miles Per Gallon",
color = "Cylinders" # This renames the legend title
) +
theme_light()
print(enhanced_plot)
ggsave("scatterplot_enhanced.png", width = 8, height = 5)

Note: We use factor(cyl) to treat the number of cylinders as a discrete categorical variable, which is appropriate for color mapping.

To visualize the relationships between multiple variables at once, the pairs() function from base R is functional but dated. A modern, ggplot2-based alternative is the ggpairs() function from the GGally package.

# install.packages("GGally")
library(GGally)
# Create a scatterplot matrix for selected variables
matrix_plot <- ggpairs(
input_data,
columns = c('mpg', 'wt', 'cyl'),
aes(color = factor(gear), alpha = 0.5), # Global aesthetic mapping
title = "Scatterplot Matrix of Car Performance Metrics"
)
print(matrix_plot)
ggsave("scatterplot_matrix.png", width = 10, height = 10)

The ggpairs plot is incredibly informative, showing:

  • Scatterplots for each pair of continuous variables.
  • Density plots along the diagonal.
  • Boxplots for continuous-vs-categorical variable pairs.
  • Correlation values.