Create a Scatter Plot

How to Make a Scatter Plot in R

Nov 2, 2026 Sheet Scatter Plot Tutorials 14 min read

A scatter plot is one of the quickest ways to see whether two numeric variables move together. In R, you can create a useful chart with a single line of code, then refine it with labels, colors, trend lines, and grouping as your analysis develops. This makes scatter plots valuable for everything from checking sales and ad spend to examining height and weight, temperature and energy use, or any other pair of measurements.

This article shows how to make a scatter plot in r using both base R and ggplot2. You will learn how to prepare a dataset, write the essential plotting code, improve readability, identify patterns, and handle common issues such as missing values or overlapping points. The examples use R’s built-in `mtcars` dataset, so you can run them immediately. By the end, you will have a dependable process for producing scatter plots that are clear enough for exploratory analysis and polished enough for reports.

Creating Your First Scatter Plot in Base R

Base R includes the `plot()` function, which is the fastest starting point for a simple scatter plot. It requires two numeric vectors: one for the horizontal x-axis and one for the vertical y-axis. In `mtcars`, `wt` represents vehicle weight and `mpg` represents miles per gallon.

“`r

plot(mtcars$wt, mtcars$mpg)

“`

Each point represents one car. The chart places weight on the x-axis and fuel efficiency on the y-axis. You should immediately notice a negative relationship: heavier cars generally return fewer miles per gallon.

You can make the same plot using a formula. This format is especially convenient when your data is stored in a data frame because it clearly describes the relationship you want to examine.

“`r

plot(mpg ~ wt, data = mtcars)

“`

The variable before the tilde appears on the y-axis, while the variable after it appears on the x-axis. That order is easy to reverse accidentally, so it is worth checking the axis labels before interpreting your chart.

Adding Labels and Basic Styling

A default scatter plot is functional, but it often needs context before you share it. Use `main`, `xlab`, and `ylab` to provide a descriptive title and axis labels. Good labels state what is being measured and, where relevant, include units.

“`r

plot(

mtcars$wt,

mtcars$mpg,

main = “Vehicle Weight and Fuel Efficiency”,

xlab = “Weight in 1,000 Pounds”,

ylab = “Miles per Gallon”,

pch = 19,

col = “steelblue”

)

“`

The `pch` argument controls the point symbol. A value of `19` produces filled circles, which are usually easier to see than the default open circles. The `col` argument sets the point color; choose a restrained color that remains readable when printed or viewed by people with color-vision differences.

Useful base R options include:

  • `cex` changes point size. For example, `cex = 1.2` makes points slightly larger.
  • `xlim` and `ylim` set visible axis ranges when you need consistent scales across multiple charts.
  • `las = 1` displays axis labels horizontally.
  • `bty = "l"` removes the top and right plot borders for a lighter visual style.
  • `grid()` adds reference lines after you create the plot.

Using ggplot2 for More Flexible Charts

The ggplot2 package is a popular choice when you need consistent styling, layered charts, or publication-ready output. Its syntax maps variables to visual properties through `aes()`, then adds chart elements with functions such as `geom_point()`.

Install ggplot2 once if it is not already available, then load it in each new R session.

“`r

install.packages(“ggplot2”)

library(ggplot2)

“`

Here is the ggplot2 version of the weight and fuel-efficiency example.

“`r

ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point()

“`

This code starts with the data frame, maps `wt` to x and `mpg` to y, and adds a layer of points. Compared with base R, ggplot2 takes a little more typing for a basic graph, but it becomes more convenient as your visualization needs grow.

Improving a ggplot2 Scatter Plot

A meaningful title, readable labels, and a clean theme help readers interpret the relationship without guessing. You can also control point size, transparency, and color directly inside `geom_point()`.

“`r

ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point(color = “steelblue”, size = 3, alpha = 0.75) +

labs(

title = “Vehicle Weight and Fuel Efficiency”,

x = “Weight in 1,000 Pounds”,

y = “Miles per Gallon”

) +

theme_minimal()

“`

The `alpha` setting makes points semi-transparent. This is helpful when many observations occupy similar positions because darker areas reveal where points overlap. The `theme_minimal()` theme removes visual clutter while keeping the chart easy to read.

Before styling any scatter plot, make sure the underlying data supports the comparison. Variable types, missing values, and units can all affect the result. For more help preparing data frames, add a relevant resource such as [Internal Link: Cleaning Data in R].

Quick Plot Setup Checklist

  • Confirm that both plotted variables are numeric.
  • Put the likely explanatory variable on the x-axis.
  • Use labels that describe the measurement and units.
  • Check for missing or impossible values before plotting.
  • Choose point sizes and colors that remain readable at the final display size.
  • Use a descriptive title when the chart will appear outside your analysis notebook.

Mapping Groups to Color and Shape

A scatter plot becomes more informative when it shows categories as well as numeric relationships. In `mtcars`, the `cyl` column records the number of cylinders. You can convert it to a factor and use color to distinguish vehicle groups.

“`r

mtcars$cyl <- factor(mtcars$cyl)

ggplot(mtcars, aes(x = wt, y = mpg, color = cyl)) +

geom_point(size = 3) +

labs(

title = “Fuel Efficiency by Vehicle Weight and Cylinder Count”,

x = “Weight in 1,000 Pounds”,

y = “Miles per Gallon”,

color = “Cylinders”

) +

theme_minimal()

“`

Color highlights a useful pattern in this example: cars with more cylinders often weigh more and have lower fuel efficiency. The legend is created automatically because `color = cyl` is mapped inside `aes()`.

You can use shape as a second grouping signal, although too many shapes make a chart difficult to scan. Reserve it for a small number of categories or use it alongside color when your chart may be printed in grayscale.

“`r

ggplot(mtcars, aes(x = wt, y = mpg, color = cyl, shape = cyl)) +

geom_point(size = 3) +

theme_minimal()

“`

Avoid mapping a continuous variable to shape. Shapes are designed for discrete groups, and ggplot2 will warn you if you try to use a numeric variable without converting it to a factor.

Showing a Continuous Variable with Color

Color can also represent a third numeric variable. For instance, you could plot weight against fuel efficiency and use horsepower to color each point. A gradient helps reveal whether a third measure changes across the same pattern.

“`r

ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) +

geom_point(size = 3) +

scale_color_viridis_c() +

labs(

title = “Weight, Fuel Efficiency, and Horsepower”,

x = “Weight in 1,000 Pounds”,

y = “Miles per Gallon”,

color = “Horsepower”

) +

theme_minimal()

“`

The `viridis` color scale is a strong default because it has good contrast and is generally more accessible than rainbow-style gradients. If you need a comparable scatter plot in a wider reporting workflow, [Internal Link: Data Visualization Best Practices] can help you select colors and chart types consistently.

Formatting Choices for Different Data Types

| Data situation | Recommended approach | Reason |

| — | — | — |

| Two numeric variables | Standard points | Shows the overall relationship clearly |

| Numeric variables with groups | Color or shape by category | Reveals differences between groups |

| Many overlapping observations | Smaller points with transparency | Shows density without hiding records |

| A third numeric variable | Color gradient or point size | Adds another dimension cautiously |

| Many groups | Facets instead of many colors | Keeps categories easier to compare |

Adding a Trend Line

A trend line summarizes the average direction of the relationship. In ggplot2, `geom_smooth()` can add a fitted line and, by default, a confidence band. For a straight linear regression line, set `method = “lm”`.

“`r

ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point(color = “steelblue”, size = 3) +

geom_smooth(method = “lm”, se = TRUE, color = “firebrick”) +

labs(

title = “Linear Trend Between Vehicle Weight and Fuel Efficiency”,

x = “Weight in 1,000 Pounds”,

y = “Miles per Gallon”

) +

theme_minimal()

“`

The shaded area represents uncertainty around the fitted trend, not the range where all future observations will fall. It is useful for showing that the line is estimated from data rather than directly observed.

Base R can add a linear trend line as well. First create the plot, then fit a model with `lm()` and add it using `abline()`.

“`r

plot(mpg ~ wt, data = mtcars, pch = 19, col = “steelblue”)

model <- lm(mpg ~ wt, data = mtcars)

abline(model, col = “firebrick”, lwd = 2)

“`

A straight line is not always appropriate. If the pattern curves, consider a smoother rather than forcing a linear story onto the data. In ggplot2, leave out `method = “lm”` to use the default local smoothing approach for many datasets.

Faceting Scatter Plots by Category

Facets split one chart into smaller panels based on a categorical variable. They are often clearer than trying to compare many groups with colors alone. For example, this chart creates a separate panel for each number of cylinders.

“`r

ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point(color = “steelblue”, size = 2.5) +

facet_wrap(~ cyl) +

labs(

title = “Vehicle Weight and Fuel Efficiency by Cylinder Count”,

x = “Weight in 1,000 Pounds”,

y = “Miles per Gallon”

) +

theme_minimal()

“`

Keep the same axis scale across facets when direct comparison matters. Free scales can make each individual panel easier to inspect, but they can also make differences between groups look larger or smaller than they really are.

Faceting works best with a modest number of meaningful groups. If you create dozens of panels, readers may struggle to compare them. In that situation, filter to the most relevant categories, summarize the data first, or build an interactive view for exploration.

Practical Steps for Building a Reliable Scatter Plot

1. Choose two measures that can reasonably be compared. A scatter plot is intended for paired numeric observations, not unrelated totals from different sources.

2. Inspect the data structure with `str(your_data)` and review summary statistics with `summary(your_data)`. This catches character columns, missing values, and unusual ranges early.

3. Start with a plain plot. Look for broad direction, clusters, outliers, and empty regions before adding styling or a model.

4. Add labels and units. A chart labeled only “x” and “y” may be technically correct but has little value in a report or presentation.

5. Add groups, a trend line, or facets only when they answer a specific analytical question. Extra visual encodings should clarify the pattern, not decorate the plot.

6. Review the finished graphic at its final size. Small labels, faint points, and crowded legends often become obvious only when the chart is exported.

Handling Missing Values and Overplotting

Missing values are common in real datasets. ggplot2 generally removes rows with missing values in variables needed for a layer, often with a warning. You can remove incomplete rows before plotting so you know exactly what data remains.

“`r

clean_data <- na.omit(mtcars[, c(“wt”, “mpg”)])

ggplot(clean_data, aes(x = wt, y = mpg)) +

geom_point()

“`

For a larger dataset, use a more targeted approach than `na.omit()` when possible. Removing every row with any missing value may discard valid observations from columns unrelated to your plot. Packages such as dplyr make it easy to filter only the variables you need.

Overplotting occurs when many points overlap and hide the true number of observations. Lowering opacity is the simplest solution. You can also add a small amount of random displacement with jitter, though you should use it carefully because it slightly changes displayed positions.

“`r

ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_jitter(width = 0.05, height = 0.05, alpha = 0.7) +

theme_minimal()

“`

For very large datasets, consider `geom_bin2d()` or `geom_hex()` instead of individual points. These display counts or densities in small grid cells, making dense regions easier to identify.

Common Scatter Plot Mistakes

A scatter plot can be visually attractive while still being misleading. One common mistake is treating correlation as proof that one variable causes another. A visible relationship may be explained by a third factor, selection bias, timing, or coincidence.

Another mistake is using an axis range that exaggerates minor differences. Narrow ranges are not always wrong, but readers should be able to see the full context. Be deliberate about axis limits, especially when comparing charts in the same report.

Watch for these issues:

  • Plotting aggregated values when individual observations are needed.
  • Adding a regression line without checking whether a linear relationship is plausible.
  • Using too many colors, shapes, or labels at once.
  • Leaving out units, especially for measurements such as revenue, dates, distance, or temperature.
  • Ignoring extreme points that may be errors, rare cases, or analytically important outliers.
  • Treating a sparse sample as evidence of a strong general pattern.

Interpreting What the Plot Shows

Start by looking at direction. An upward pattern suggests a positive association, while a downward pattern suggests a negative association. A cloud with no obvious slope may indicate little linear relationship, though a curved or segmented pattern could still exist.

Then look for form, strength, clusters, and outliers. A tight line-like pattern indicates a stronger association than a broad cloud. Separate clusters may reveal groups in the data, and unusual points can signal errors or important exceptions worth investigating.

A scatter plot is a starting point for analysis, not the final verdict. Pair it with descriptive statistics, domain knowledge, and an appropriate model when decisions depend on the result. For example, a trend line may summarize the relationship, but it does not automatically establish causation or predict well beyond the observed range.

Saving Your Scatter Plot

In RStudio, you can use the Export button in the Plots pane for a quick manual download. For reproducible work, save files in your script with `ggsave()`. This ensures that the same chart can be generated again with consistent dimensions.

“`r

plot_mpg_weight <- ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point(color = “steelblue”, size = 3) +

theme_minimal()

ggsave(

filename = “weight-vs-mpg.png”,

plot = plot_mpg_weight,

width = 8,

height = 5,

dpi = 300

)

“`

A width of eight inches, height of five inches, and 300 DPI is a dependable starting point for many reports and print uses. For web publishing, PNG works well for most charts; PDF or SVG may be better when you need scalable vector output.

Conclusion

A useful scatter plot starts with two well-chosen numeric variables and a clear question about their relationship. Base R gives you a fast route to an exploratory chart with `plot()`, while ggplot2 provides more control over labels, themes, groups, facets, and trend lines. In either approach, thoughtful axis labels and sensible styling matter more than visual decoration.

As you make a scatter plot in r, begin with the simplest version and inspect the data before adding layers. Look for direction, clusters, overlap, and unusual observations, then use color, transparency, faceting, or smoothing only when they make the pattern easier to interpret. Check missing values, avoid overstating what correlation means, and save the finished chart at a suitable size for its destination. With that workflow, scatter plots become a practical way to turn raw measurements into evidence you can explain clearly.

Frequently Asked Questions

Can I make a scatter plot without ggplot2?

Yes. Base R includes the `plot()` function, so no additional package is required. Use `plot(y ~ x, data = your_data)` for a quick chart, then add labels and styling with optional arguments.

How do I add a regression line in R?

Use `geom_smooth(method = “lm”)` in ggplot2 to add a linear regression line and confidence band. In base R, fit a model with `lm()` and pass it to `abline()` after creating the plot.

What does alpha mean in a scatter plot?

Alpha controls point transparency. Values closer to zero make points more transparent, while one is fully opaque. It is especially useful when many observations overlap and you need dense areas to appear darker.

Why are my scatter plot points missing?

Missing points often result from `NA` values, axis limits that exclude observations, or nonnumeric data. Check your data with `summary()` and `str()`, then remove or address missing values in the plotted columns.

When should I use a scatter plot?

Use a scatter plot when you want to examine the relationship between two numeric variables measured for the same observations. It is useful for spotting trends, clusters, outliers, and possible associations before modeling.