Scatter Plot in R Using ggplot2: A Complete Step-by-Step Guide
A scatter plot displays the relationship between two numerical variables. This practical R and ggplot2 guide shows you how to create, customise and interpret scatter plots using built-in datasets and downloadable sample data.
This tutorial is part of the ggplot2 tutorial. It is designed for R beginners, students, researchers and data analysts who want to create professional scatter plots using ggplot2 in R. You will work with the built-in mpg dataset and downloadable CSV datasets supplied with this lesson.
1. What is a scatter plot?
A scatter plot (also called a scatter diagram or scatter graph) is a chart that displays the relationship between two numerical variables. Each observation is represented by a point. The horizontal position represents the value of the first variable (x), and the vertical position represents the value of the second variable (y).
For example, suppose you collect the number of hours students study and their examination scores. A scatter plot places study hours on the x-axis and exam score on the y-axis. Each student becomes one point. The pattern of points helps you see whether students who study longer tend to achieve higher scores.
What information can a scatter plot reveal?
- Direction: whether the relationship is positive, negative or shows little linear association.
- Strength: whether points are closely arranged around a pattern or widely scattered.
- Form: whether the pattern is linear, curved or more complex.
- Clusters: whether observations form separate groups.
- Outliers: whether some observations are unusually far from the main pattern.
2. When should you use a scatter plot?
Use a scatter plot when both variables are numerical and you want to explore how they vary together. It is common in statistics, business analytics, economics, public health, education, engineering and machine learning.
| Field | X variable | Y variable | Question |
|---|---|---|---|
| Education | Study hours | Exam score | Do students who study more tend to score higher? |
| Marketing | Advertising spend | Sales revenue | Is advertising expenditure associated with sales? |
| Public health | Age | Blood pressure | How does blood pressure vary with age? |
| Economics | Income | Consumption | How does consumption vary with income? |
| Environment | Temperature | Electricity use | Does electricity demand change with temperature? |
| Machine learning | Feature 1 | Feature 2 | Are observations separated into visible clusters? |
3. How to create a scatter plot in R using ggplot2
The ggplot2 package is one of the most widely used R packages for data visualisation. A basic scatter plot needs three things: a data frame, x and y mappings, and the point geom.
Step 1: Install and load ggplot2
# Run this once if ggplot2 is not installed
install.packages("ggplot2")
# Load the package in each new R session
library(ggplot2)
Step 2: Choose your dataset
For the first example, use mpg, a dataset included with ggplot2. It contains fuel economy and vehicle characteristics for different car models.
data("mpg")
# Inspect the first six rows
head(mpg)
# Check the variable names and data types
str(mpg)
# View the available columns
names(mpg)
Step 3: Map x and y
We will use displ (engine displacement in litres) as x and hwy (highway miles per gallon) as y.
ggplot(data = mpg, aes(x = displ, y = hwy))
This starts a plot and defines the two axes, but it does not yet draw points.
Step 4: Add geom_point()
ggplot(data = mpg, aes(x = displ, y = hwy)) +
geom_point()
geom_point() draws one point for each observation. The + operator adds a layer to the ggplot object.
Step 5: Add a title and axis labels
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
labs(
title = "Engine Size and Highway Fuel Economy",
x = "Engine displacement (litres)",
y = "Highway fuel economy (miles per gallon)"
)
Clear labels make the chart understandable without requiring the reader to know the dataset's variable names.
4. Scatter plot examples using the built-in mpg dataset
The mpg dataset is useful for learning because it includes several numerical and categorical variables. You can explore engine size, city and highway fuel economy, vehicle class, manufacturer and drive type.
Example 1: Engine size versus highway fuel economy
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point()
Look for the overall direction and spread of the points. A downward pattern suggests that larger engine displacement tends to be associated with lower highway fuel economy in this dataset.
Example 2: City fuel economy versus highway fuel economy
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point() +
labs(
title = "City versus Highway Fuel Economy",
x = "City MPG",
y = "Highway MPG"
)
Example 3: Engine size versus city fuel economy
ggplot(mpg, aes(displ, cty)) +
geom_point(colour = "darkorange", size = 2.5)
Example 4: Use manufacturer as a grouping variable
ggplot(mpg, aes(displ, hwy, colour = manufacturer)) +
geom_point()
This example may produce many legend entries because there are many manufacturers. For a simpler comparison, use a variable with fewer categories, such as drv or class.
5. Customise a ggplot2 scatter plot: point colour, size and shape
After creating the basic scatter plot, you can customise how points look. Remember the distinction between a fixed setting and an aesthetic mapping: a fixed colour is written outside aes(); a variable mapped to colour is written inside aes().
Set one colour for all points
ggplot(mpg, aes(displ, hwy)) +
geom_point(colour = "steelblue", size = 3)
Change point size and transparency
ggplot(mpg, aes(displ, hwy)) +
geom_point(
colour = "#2878B5",
size = 2.8,
alpha = 0.65
)
Use a custom theme
ggplot(mpg, aes(displ, hwy)) +
geom_point(colour = "#2878B5", size = 2.5) +
labs(
title = "Engine Size and Fuel Economy",
x = "Engine displacement (litres)",
y = "Highway MPG"
) +
theme_minimal()
6. Create a scatter plot with colour or shape by group
When your dataset includes a categorical variable, you can map it to colour or shape. This lets readers compare groups in the same scatter plot.
Colour points by vehicle class
ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point(size = 2.5, alpha = 0.8) +
labs(colour = "Vehicle class")
Use shape to distinguish groups
ggplot(mpg, aes(displ, hwy, shape = drv)) +
geom_point(size = 3)
Use both colour and shape
ggplot(mpg, aes(displ, hwy,
colour = drv,
shape = drv)) +
geom_point(size = 2.8)
Using both encodings for the same variable can help readers distinguish groups, including in some greyscale or colour-vision contexts. Do not map too many different categories to shape because symbols become difficult to distinguish.
7. Map point size to a numerical variable
You can represent a third numerical variable by changing point size. This creates a bubble-style scatter plot.
ggplot(mpg, aes(x = displ, y = hwy, size = cty)) +
geom_point(alpha = 0.6) +
labs(size = "City MPG")
For example, x can represent engine displacement, y can represent highway fuel economy, and point size can represent city fuel economy. This adds another dimension, but the chart may become harder to read if points overlap.
For a bubble chart, explain what point size represents in the legend and avoid extreme size differences that hide smaller points.
8. Reduce overlapping points with alpha transparency
When many observations have similar x and y values, points overlap. This is called overplotting. Opaque points can hide one another and make dense areas look like a single mark.
Set alpha to a value between 0 and 1. Lower values make points more transparent, so overlapping regions become darker.
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.3)
For very large datasets, consider smaller points, hexagonal binning or a two-dimensional density display. Transparency is a simple first improvement, not always a complete solution.
9. Add a regression line or smooth curve to a scatter plot
A trend line helps summarise the relationship between x and y. In ggplot2, geom_smooth() estimates a trend and adds it to the plot.
Add a linear regression line
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.65) +
geom_smooth(method = "lm", se = TRUE)
method = "lm" fits a linear model. The shaded band is the default confidence interval around the estimated mean trend. Use se = FALSE to remove the band.
Add a LOESS smooth curve
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.65) +
geom_smooth(method = "loess", se = TRUE)
LOESS can represent a curved pattern without requiring you to specify a straight-line relationship. It is often useful for exploratory analysis of smaller datasets.
Fit separate regression lines for groups
ggplot(mpg, aes(displ, hwy, colour = drv)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
Because colour is mapped to drv, ggplot2 fits a separate line for each group. You can use aes(group = drv) when you need to define grouping explicitly.
10. Calculate and display the correlation coefficient
A scatter plot is often used alongside a correlation coefficient. Pearson's correlation measures the strength and direction of a linear association between two numerical variables. Its value ranges from -1 to +1.
- Positive value: larger x values tend to occur with larger y values.
- Negative value: larger x values tend to occur with smaller y values.
- Near zero: little linear association; a curved relationship may still exist.
Calculate Pearson correlation in R
cor(mpg$displ, mpg$hwy,
use = "complete.obs",
method = "pearson")
Calculate Spearman correlation
cor(mpg$displ, mpg$hwy,
use = "complete.obs",
method = "spearman")
Spearman correlation is based on ranks and can be useful for monotonic relationships or when Pearson's assumptions are not suitable.
Add a correlation value to the chart
r_value <- cor(mpg$displ, mpg$hwy,
use = "complete.obs")
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
annotate(
"text",
x = 6,
y = 40,
label = paste("Pearson r =", round(r_value, 2)),
hjust = 1
)
11. Create multiple scatter plots using facet_wrap()
When a dataset contains groups, you can create a separate panel for each group using facet_wrap(). This is often clearer than placing many colours and symbols in one crowded chart.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~ class) +
labs(
title = "Engine size and fuel economy by vehicle class",
x = "Engine displacement",
y = "Highway MPG"
)
Use facet_wrap() for one grouping variable. Use facet_grid() when you want panels arranged by two categorical variables.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_grid(drv ~ cyl)
12. Add labels and annotate important observations
Labels can identify selected observations, but adding a label to every point often creates clutter. Use geom_text() or geom_label() for a small number of important cases.
# Label selected vehicle observations
selected_cars <- subset(mpg, manufacturer == "audi")
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.5) +
geom_text(
data = selected_cars,
aes(label = model),
size = 3,
vjust = -0.6
)
For a single annotation, use annotate():
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
annotate(
"text",
x = 6,
y = 38,
label = "Higher displacement",
colour = "red"
)
When many labels are necessary, consider the ggrepel package, which helps reduce label overlap.
install.packages("ggrepel")
library(ggrepel)
ggplot(mpg, aes(displ, hwy, label = model)) +
geom_point() +
geom_text_repel()
13. Download sample datasets and create your own scatter plot data
Practise with the CSV files included in this lesson. They are designed for learning and are synthetic teaching datasets, not real student or company records.
- Download student_study_scores.csv — study hours, exam scores and study group.
- Download advertising_sales.csv — advertising spend, monthly sales and region.
- Download engine_fuel_economy_example.csv — engine displacement, highway fuel economy and vehicle category for practice.
Example A: Student study hours and exam scores
# Read the downloaded CSV file
students <- read.csv("student_study_scores.csv")
head(students)
str(students)
ggplot(students, aes(study_hours, exam_score)) +
geom_point(colour = "steelblue", size = 2.5) +
geom_smooth(method = "lm", se = TRUE) +
labs(
title = "Study Hours and Examination Scores",
x = "Study hours",
y = "Exam score (%)"
) +
theme_minimal()
Example B: Colour students by study group
ggplot(students,
aes(study_hours, exam_score,
colour = study_group)) +
geom_point(size = 2.5, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE) +
labs(colour = "Study group")
Example C: Advertising expenditure and sales
sales <- read.csv("advertising_sales.csv")
ggplot(sales,
aes(advertising_spend, monthly_sales,
colour = region)) +
geom_point(size = 2.5, alpha = 0.75) +
geom_smooth(method = "lm", se = FALSE) +
labs(
title = "Advertising Spend and Monthly Sales",
x = "Advertising spend (PKR)",
y = "Monthly sales (PKR)",
colour = "Region"
)
Example D: Create a small dataset directly in R
You do not always need an external CSV file. You can create a data frame using data.frame().
student_data <- data.frame(
study_hours = c(1, 2, 3, 4, 5, 6, 7, 8),
exam_score = c(42, 48, 51, 59, 63, 71, 76, 84)
)
ggplot(student_data,
aes(study_hours, exam_score)) +
geom_point(size = 3, colour = "darkgreen") +
geom_smooth(method = "lm", se = FALSE)
Example E: Generate a larger synthetic dataset
set.seed(123)
n <- 100
practice_data <- data.frame(
hours = runif(n, 1, 10)
)
practice_data$score <- 40 +
5 * practice_data$hours +
rnorm(n, mean = 0, sd = 8)
ggplot(practice_data, aes(hours, score)) +
geom_point(alpha = 0.7) +
geom_smooth(method = "lm")
14. Advanced scatter plot examples in ggplot2
Example 1: Add a two-dimensional density layer
When a dataset contains many observations, a two-dimensional density layer can help show where points are concentrated.
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.35) +
geom_density_2d(colour = "red")
Example 2: Use a log scale
If a variable has a strongly skewed distribution or spans several orders of magnitude, a logarithmic axis may make the pattern easier to inspect. Only use it when a log transformation is meaningful for the data.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
scale_y_log10()
Example 3: Add a reference line
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_hline(yintercept = 25,
linetype = "dashed",
colour = "red")
Example 4: Export a high-quality scatter plot
p <- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point(size = 2.5) +
geom_smooth(method = "lm", se = FALSE) +
theme_minimal()
ggsave(
filename = "my-scatter-plot.png",
plot = p,
width = 8,
height = 5,
dpi = 300
)
ggsave() saves the plot to a file. A width of 8 inches, height of 5 inches and resolution of 300 DPI is a useful starting point for many reports.
15. How to interpret a scatter plot
After creating a scatter plot, describe the pattern systematically. Do not report only that the points go up or down. Consider direction, form, strength, clusters and unusual observations.
| Pattern | What it may indicate | What to check |
|---|---|---|
| Positive association | Higher x values tend to occur with higher y values. | Is the pattern approximately linear? |
| Negative association | Higher x values tend to occur with lower y values. | Are there influential outliers? |
| Little linear association | No clear straight-line pattern. | Could the relationship be curved or grouped? |
| Curved pattern | The relationship may be non-linear. | Would a smooth curve describe it better? |
| Clusters | Subgroups may exist in the observations. | Do groups correspond to a meaningful category? |
| Outliers | Some observations differ from the main pattern. | Are they errors, rare cases or influential observations? |
Example interpretation
If a scatter plot of study hours and examination scores shows an upward pattern, you may describe it as a positive association: students with more study hours tend to have higher scores in this sample. You should not conclude that study time alone caused the score difference without considering other factors and the study design.
16. Common scatter plot mistakes and how to avoid them
1. Using a categorical variable as a continuous axis
Check the data type and meaning of your variables. A category such as department or vehicle class may be better represented through colour, shape or facets.
2. Mapping a fixed colour inside aes()
# Not the intended way to set one fixed blue colour
ggplot(mpg, aes(displ, hwy, colour = "blue")) +
geom_point()
# Correct: fixed colour outside aes()
ggplot(mpg, aes(displ, hwy)) +
geom_point(colour = "blue")
3. Hiding points through overplotting
Reduce point size, use alpha transparency or consider a density-based chart when many observations overlap.
4. Adding too many groups
A legend with dozens of categories is difficult to read. Use a smaller number of meaningful groups or create facets.
5. Assuming correlation proves causation
Correlation measures association. It does not establish a causal relationship.
6. Using a regression line without checking the pattern
A straight line may be misleading when the relationship is curved, has distinct subgroups or is dominated by outliers. Inspect the points first.
7. Forgetting missing values
Check missing values with sum(is.na(data$variable)) and decide how to handle them. Do not remove observations automatically without understanding why values are missing.
17. Scatter plot practice exercises with solutions
Use the built-in mpg dataset and the downloadable student and advertising CSV files.
- Create a scatter plot of
displagainsthwy. - Change all points to dark green and set their size to 3.
- Map
classto point colour. - Add a linear regression line and hide its confidence band.
- Calculate Pearson correlation between
displandhwy. - Create separate panels for each vehicle class using
facet_wrap(). - Read
student_study_scores.csvand colour the points bystudy_group. - Create an advertising spend versus sales scatter plot and fit separate trend lines by region.
Show suggested R solutions
# 1. Basic scatter plot
ggplot(mpg, aes(displ, hwy)) +
geom_point()
# 2. Fixed colour and size
ggplot(mpg, aes(displ, hwy)) +
geom_point(colour = "darkgreen", size = 3)
# 3. Map colour to class
ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()
# 4. Add a linear trend without confidence band
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
# 5. Pearson correlation
cor(mpg$displ, mpg$hwy,
use = "complete.obs")
# 6. Facets
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~ class)
# 7. Student sample data
students <- read.csv("student_study_scores.csv")
ggplot(students,
aes(study_hours, exam_score,
colour = study_group)) +
geom_point()
# 8. Advertising data with separate trend lines
sales <- read.csv("advertising_sales.csv")
ggplot(sales,
aes(advertising_spend, monthly_sales,
colour = region)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
18. Summary: creating scatter plots in R with ggplot2
A scatter plot is a fundamental tool for exploring relationships between numerical variables. With ggplot2, the basic structure is simple: specify the dataset, map x and y inside aes(), and add geom_point(). You can then improve the chart with colour, shape, size, transparency, regression lines, correlation labels and facets.
ggplot(data, aes(x = numeric_variable_1,
y = numeric_variable_2)) +
geom_point()
Start with this structure and add only the layers that improve your analysis or communicate an important result.Continue learning: explore the other lessons in the ggplot2 tutorial to learn about aesthetics, geoms, statistical transformations, scales and themes.
ggplot2 FAQ
How do I create a scatter plot in R using ggplot2?
Load ggplot2, pass your data to ggplot(), map the x and y variables inside aes(), and add geom_point(). For example: ggplot(mpg, aes(displ, hwy)) + geom_point().
What is a scatter plot used for?
A scatter plot is used to explore the relationship between two numerical variables, identify trends, clusters, unusual observations and possible outliers.
How do I add a regression line to a ggplot2 scatter plot?
Add geom_smooth(method = 'lm', se = TRUE) to the scatter plot. Use se = FALSE if you do not want the confidence band.
How do I change point colour in ggplot2?
Use colour = 'steelblue' outside aes() to set one fixed colour, or map a variable inside aes(colour = group) to colour points by a data column.
How do I add a correlation coefficient to a scatter plot?
Calculate the correlation using cor() and add the result as a label with annotate() or geom_text(). Remember that correlation describes association, not causation.
What is the difference between a scatter plot and a line graph?
A scatter plot shows individual pairs of values without connecting them. A line graph connects observations in a meaningful order, often time.
Can I create a scatter plot with categorical groups?
Yes. Map a categorical variable to colour or shape, or use facet_wrap() to create separate panels for each group.
Which dataset can I use to practise scatter plots in R?
The ggplot2 package includes datasets such as mpg and economics. This lesson also provides downloadable CSV sample datasets for student scores and advertising sales.