How to Create a Scatter Plot in RStudio: Step-by-Step Guide

A scatter plot is one of the simplest ways to compare two numeric variables. It helps show patterns, relationships, gaps, clusters, and unusual values that may not be obvious inside a spreadsheet or raw data table.

If you work with data in R Studio, scatter plots are useful for quick checks and polished reporting. They can support academic work, business analysis, research dashboards, marketing reports, and any project where two measurements need comparison.

This guide explains how to create a scatter plot in R Studio using base R and ggplot2. It also covers data preparation, labels, colors, trend lines, common errors, and practical formatting steps for cleaner visual results.

Getting Your Data Ready

Before creating a scatter plot, your data should be organized in a clear tabular format. Each row should represent one observation, while each column should store a variable such as sales, age, height, price, distance, or revenue.

Scatter plots work with numeric values on both axes. If one of your columns is stored as text, R may not plot it correctly. Checking column types before plotting can prevent errors and confusing visual output.

You can use built-in datasets, imported CSV files, or manually created data frames. For practice, built-in datasets are helpful because they already contain clean numeric columns that are easy to plot in R Studio.

Key Data Checks Before Plotting

  • Confirm both x-axis and y-axis columns are numeric.
  • Remove or review missing values before plotting.
  • Check for spelling errors in column names.
  • Use clear variable names that are easy to read.
  • Keep one observation per row for cleaner plotting.
  • Review extreme values because they can stretch the chart scale.

Creating a Basic Scatter Plot with Base R

Base R includes a simple plot function that can create a scatter plot without installing extra packages. This is useful when you need a quick chart, a fast visual check, or a lightweight approach inside an R script.

You can create a scatter plot by passing one numeric variable to the x-axis and another to the y-axis. The plot function automatically draws points and creates basic axes, making it a good starting point for beginners.

For example, the built-in mtcars dataset contains car performance data. You can compare car weight and miles per gallon to see whether heavier cars tend to have lower fuel efficiency across the dataset.

Base R Scatter Plot Example

plot(mtcars$wt, mtcars$mpg)

This command places car weight on the x-axis and miles per gallon on the y-axis. R Studio displays the chart in the Plots pane, where you can view, export, or adjust it further.

The default chart is basic, but it already shows the relationship between the two variables. In this case, the points generally move downward as car weight increases, suggesting heavier cars often have lower fuel economy.

Adding Titles and Axis Labels

A scatter plot becomes much easier to read when it has a clear title and labeled axes. Without labels, readers may not know what the points represent, especially when the chart appears outside your R script.

Base R allows you to add labels directly inside the plot function. You can use main for the chart title, xlab for the horizontal axis, and ylab for the vertical axis.

Clear labels should describe the data in plain language. Instead of short column names like wt and mpg, use labels such as Car Weight and Miles Per Gallon so the chart works for a wider audience.

Base R Labeled Plot Example

plot(

mtcars$wt,

mtcars$mpg,

main = “Car Weight and Fuel Efficiency”,

xlab = “Car Weight”,

ylab = “Miles Per Gallon”

)

This version is more useful for reports because readers can quickly see what the chart compares. Good labeling also helps when charts are shared as images, slides, or screenshots without surrounding code.

Changing Point Colors and Shapes

Color and shape can make a scatter plot easier to scan. In base R, the col argument changes point color, while pch changes point style. These small adjustments can improve readability without making the chart complicated.

You can use simple color names such as blue, red, darkgreen, or black. For point shapes, R uses numeric codes. A common choice is pch = 19, which creates solid circles that are easy to see.

Color should support the message of the chart. A single strong color often works better than many colors when you are only comparing two numeric variables and do not need group categories.

Simple Style Example

plot(

mtcars$wt,

mtcars$mpg,

main = “Car Weight and Fuel Efficiency”,

xlab = “Car Weight”,

ylab = “Miles Per Gallon”,

col = “steelblue”,

pch = 19

)

This chart keeps the structure simple while improving the visual style. The filled blue points are easier to read than the default hollow circles, especially when the chart is used in a presentation or article.

Creating a Scatter Plot with ggplot2

The ggplot2 package is widely used for data visualization in R. It gives you more control over styling, layers, themes, legends, and grouped data. For polished charts, ggplot2 is usually the better choice.

If ggplot2 is not installed, you can install it with install.packages(“ggplot2”). After installation, load it with library(ggplot2). Once loaded, you can build scatter plots with a clean layered structure.

The basic idea is simple. You provide the dataset, map variables to axes with aes, and add points with geom_point. This structure makes it easier to expand charts later with colors, lines, and themes.

ggplot2 Scatter Plot Example

library(ggplot2)

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

geom_point()

This creates the same basic comparison between car weight and fuel efficiency. The result usually looks cleaner than a base R default chart and gives you a flexible foundation for customization.

Adding Labels in ggplot2

Labels in ggplot2 are added with the labs function. You can define the chart title, subtitle, x-axis label, y-axis label, and caption. This makes the final chart easier to use in articles, notebooks, and reports.

A good title should state what the chart compares. A subtitle can add context, such as the dataset or sample group. Axis labels should use readable language rather than raw variable names.

For related chart formatting ideas, our data visualization guide can help you choose colors, labels, and layouts that fit different reporting goals. Strong chart design depends on both accurate code and readable presentation.

Labeled ggplot2 Example

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

geom_point(color = “steelblue”) +

labs(

title = “Car Weight and Fuel Efficiency”,

subtitle = “Comparison using the mtcars dataset”,

x = “Car Weight”,

y = “Miles Per Gallon”

)

This chart gives readers more context without crowding the visual. The subtitle explains where the data comes from, while the axis labels make the variables clear even for someone who has never seen the dataset.

Using Color Groups in a Scatter Plot

Scatter plots become more informative when points are grouped by a category. In ggplot2, you can map color to a variable inside aes. This creates separate colors and a legend automatically.

For example, the mtcars dataset includes the number of cylinders for each car. Coloring points by cylinders can show whether different engine groups follow different fuel efficiency patterns across car weights.

When using grouped colors, choose a category with a manageable number of groups. Too many colors can make the plot harder to read. Three to six groups usually work well for most simple scatter plots.

Grouped Color Example

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

geom_point(size = 3) +

labs(

title = “Car Weight, Fuel Efficiency, and Cylinders”,

x = “Car Weight”,

y = “Miles Per Gallon”,

color = “Cylinders”

)

The factor function treats cylinders as categories instead of continuous numbers. This helps ggplot2 create a clean legend with separate groups, making the chart easier to interpret for readers.

Adding a Trend Line

A trend line can help show the general direction of the relationship between two variables. In ggplot2, geom_smooth adds a fitted line to the scatter plot, which can make patterns easier to see.

For a simple linear trend, use method = “lm”. This draws a straight regression line through the data. You can also remove the shaded confidence band by setting se = FALSE.

Trend lines are useful, but they should be used carefully. A line can suggest a relationship, but it does not prove cause and effect. The chart should be paired with proper analysis when making important decisions.

Trend Line Example

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

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

geom_smooth(method = “lm”, se = FALSE, color = “darkred”) +

labs(

title = “Car Weight and Fuel Efficiency Trend”,

x = “Car Weight”,

y = “Miles Per Gallon”

)

This chart shows both individual points and the general downward trend. Readers can see the raw data while also getting a quick view of the broader relationship between weight and fuel efficiency.

Handling Missing Values

Missing values can affect charts in R Studio. If your x-axis or y-axis column contains NA values, R may remove those rows during plotting or show a warning message in the console.

In many cases, the warning simply means some rows were skipped because they lacked values. Still, it is better to review missing data before plotting so your chart reflects the data quality clearly.

You can remove missing rows with na.omit or use complete.cases for selected columns. The right choice depends on your analysis. Sometimes missing data should be removed, while other times it should be investigated first.

Missing Value Example

clean_data <- mtcars[complete.cases(mtcars[,

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

geom_point()

This creates a plot using rows where both weight and miles per gallon are available. It keeps the plotting step cleaner and makes it easier to explain how the data was prepared.

Importing a CSV File for Scatter Plots

Many real projects begin with a CSV file rather than a built-in dataset. In R Studio, you can import a CSV file using read.csv and store it as a data frame for plotting.

Your CSV file should have column names in the first row. After importing, use functions like head, str, and summary to review the structure before creating a scatter plot.

For more R workflow help, our R programming tutorials cover importing files, checking data frames, and building reusable scripts. Clean import habits save time when your datasets become larger or less predictable.

CSV Import Example

data <- read.csv("sales_data.csv")

head(data)

str(data)

ggplot(data, aes(x = advertising_spend, y = revenue)) +

geom_point(color = “steelblue”) +

labs(

title = “Advertising Spend and Revenue”,

x = “Advertising Spend”,

y = “Revenue”

)

This example assumes your CSV contains advertising_spend and revenue columns. If your column names are different, replace those names with the exact columns from your imported data frame.

Customizing Themes

Themes control the overall appearance of a ggplot2 chart. They affect background color, grid lines, axis text, legend style, and spacing. A clean theme can make a scatter plot feel more professional.

Common options include theme_minimal, theme_classic, and theme_bw. The minimal theme is often useful for reports because it reduces visual clutter while keeping light grid lines for easy reading.

You can also adjust text size, title placement, and legend position. These changes matter when charts are used in slides, dashboards, blog posts, or printed reports where readability is important.

Theme Example

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

geom_point(size = 3) +

theme_minimal() +

labs(

title = “Fuel Efficiency by Car Weight”,

x = “Car Weight”,

y = “Miles Per Gallon”,

color = “Cylinders”

)

This version looks cleaner and more modern than the default plot. It keeps the focus on the data while still giving enough structure for readers to compare values across the chart.

Saving Your Scatter Plot

After creating a scatter plot in R Studio, you may need to save it for a report, article, or presentation. The Plots pane includes an export option, but code-based saving is more consistent.

The ggsave function saves the most recent ggplot chart to a file. You can choose formats such as PNG, JPG, or PDF. You can also set width, height, and resolution.

Saving charts with code helps keep your workflow reproducible. If the data changes later, you can rerun the script and create an updated chart with the same size, style, and file name.

Save Plot Example

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

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

theme_minimal() +

labs(

title = “Car Weight and Fuel Efficiency”,

x = “Car Weight”,

y = “Miles Per Gallon”

)

ggsave(&amp;amp;amp;quot;scatter_plot.png&amp;amp;amp;quot;,

This saves a high-resolution PNG file in your working directory. A resolution of 300 dpi is a common choice for documents and presentations where the chart should remain sharp.

Common Scatter Plot Mistakes

One common mistake is using nonnumeric data on both axes. Scatter plots are designed for numeric relationships. If one variable is categorical, another chart type such as a box plot or bar chart may be more suitable.

Another issue is overplotting, which happens when many points overlap. This can make dense datasets hard to read. Smaller point sizes, transparency, or sampling can help reveal patterns more clearly.

Poor labels can also weaken a chart. A scatter plot should not require readers to inspect the code to know what it means. Titles, axis labels, and legends should make the chart readable on its own.

Practical Fixes for Cleaner Charts

  • Use alpha transparency when many points overlap.
  • Increase point size only when the dataset is small.
  • Avoid too many colors in one chart.
  • Use readable labels instead of raw column names.
  • Add a trend line only when it supports the analysis.
  • Save charts with consistent dimensions for reports.

Using Transparency for Dense Data

When a scatter plot has many points, overlapping can hide important patterns. In ggplot2, the alpha argument controls transparency. Lower alpha values make points more transparent, helping dense areas become easier to see.

Transparency is useful for large datasets where thousands of points may sit close together. Instead of showing a solid block of color, transparent points reveal where observations are concentrated.

A good alpha value depends on the dataset size. For small datasets, 0.8 or 1 may work well. For larger datasets, values between 0.2 and 0.5 can make the chart more readable.

Transparency Example

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

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

theme_minimal() +

labs(

title = “Car Weight and Fuel Efficiency”,

x = “Car Weight”,

y = “Miles Per Gallon”

)

The mtcars dataset is small, so transparency is not essential here. Still, this example shows the syntax you can use when working with larger files, survey data, customer records, or scientific measurements.

Setting Axis Limits

Axis limits can help focus a scatter plot on the most relevant range of values. In ggplot2, you can use xlim and ylim or coord_cartesian to control the visible plotting area.

For most cases, coord_cartesian is safer because it zooms into the chart without removing data from calculations. This matters when you add trend lines or summaries that should still use the full dataset.

Axis limits should be used honestly. Do not crop a chart in a way that hides important values or changes the visual message. The goal is readability, not distortion.

Axis Limit Example

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

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

coord_cartesian(xlim = c(2, 5), ylim = c(10, 35)) +

theme_minimal() +

labs(

title = “Focused View of Car Weight and Fuel Efficiency”,

x = “Car Weight”,

y = “Miles Per Gallon”

)

This chart focuses on a specific range while keeping the data available for plotting calculations. It is useful when extreme values make the main pattern harder to see.

Reading the Scatter Plot Results

After creating the chart, look at the direction, shape, spread, and unusual points. Direction shows whether the relationship tends to rise, fall, or stay flat as the x-axis variable changes.

Shape tells you whether the relationship looks linear, curved, or grouped. Spread shows how tightly the points follow a pattern. Wide spread means the relationship may be weaker or influenced by other variables.

Unusual points deserve attention because they may represent data entry errors, rare cases, or important exceptions. A scatter plot helps you notice these values quickly, but you may need more analysis to explain them.

When to Use Base R or ggplot2

Base R is useful for quick checks, lightweight scripts, and simple charts. It requires no extra package installation and works well when you need a fast visual during early analysis.

ggplot2 is better when the chart needs polish, grouping, legends, themes, or layered design. It is also easier to extend when you want trend lines, facets, custom colors, or publication-ready styling.

Many R users use both. Base R helps during fast exploration, while ggplot2 supports final visuals. The right choice depends on your goal, deadline, and how the chart will be shared.

Conclusion

Scatter plots are practical tools for comparing two numeric variables in R Studio. They help reveal direction, spread, grouping, and unusual values while keeping the data visible in a simple visual format.

You can use base R for quick charts or ggplot2 for cleaner, more flexible visuals. Labels, colors, themes, trend lines, transparency, and saved output all help turn a basic plot into a useful reporting asset.

When learning how to create a scatter plot in R Studio, start with clean numeric data, build a simple chart, then add only the styling and context your readers need. A clear scatter plot should make the relationship easy to read without extra explanation.

FAQ

What package is used for scatter plots in R Studio

You can create scatter plots with base R using the plot function, so no package is required. For more control over labels, colors, themes, legends, and trend lines, ggplot2 is commonly used.

Can I create a scatter plot from a CSV file

Yes, you can import a CSV file with read.csv, check the column names, then pass numeric columns into plot or ggplot. Make sure the selected x-axis and y-axis columns contain numeric values.

Why is my scatter plot not showing correctly

A scatter plot may fail or look wrong if column names are misspelled, values are stored as text, or missing data affects plotting. Use str, summary, and head to review the dataset before charting.

How do I add a trend line in R Studio

In ggplot2, add geom_smooth with method = “lm” for a linear trend line. You can set se = FALSE to remove the confidence band if you want a cleaner chart.

How do I save a scatter plot as an image

Use ggsave to save a ggplot chart as PNG, JPG, or PDF. Set the file name, plot object, width, height, and dpi so the saved chart has the right size and quality.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *