how to make a scatter plot in r

How to Make a Scatter Plot in R: Easy Step-by-Step Guide

By
AD

Creating a scatter plot in R is one of the most fundamental skills for anyone starting their data visualization journey. At its core, this plot type displays the relationship between two continuous variables, using dots to represent individual data points on a two-dimensional plane. While the concept is simple, R offers multiple powerful frameworks to achieve this, each with its own strengths for customization and layering.

For the absolute basics, the base R plot function provides a quick and dirty solution without requiring any additional packages. This method is ideal for quick checks during data exploration when you need a result immediately. However, for producing publication-ready graphics or complex visual layers, the ggplot2 package is widely considered the industry standard in the R community.

Method 1: Using Base R Graphics

The base R system is always available since it is part of the standard installation, so there is no need to install anything new. The `plot()` function handles scatter plots efficiently with a straightforward syntax that feels natural to users of other statistical software.

AD
Scatter Plot Worksheet With Answers
Scatter Plot Worksheet With Answers
Making your first plot in R | R (for ecology)
Making your first plot in R | R (for ecology)
How to Make a Scatter Plot in R with Ggplot2 -
How to Make a Scatter Plot in R with Ggplot2 -

Basic Scatter Plot

To generate a simple scatter plot, you only need to pass two numeric vectors to the function. The first vector controls the horizontal axis (x-axis), while the second controls the vertical axis (y-axis).

  • plot(x_data, y_data)

This command immediately renders a graph in the plot pane of RStudio or the designated graphics device. You can easily adjust the main title, axis labels, and the point character using additional arguments within the same function call.

Excel Scatter Plot Tutorial | Step-by-Step Data Visualization Guide for Beginners
Excel Scatter Plot Tutorial | Step-by-Step Data Visualization Guide for Beginners
11 Hands-On Scatter Plot Activities (Free PDF Downloads)
11 Hands-On Scatter Plot Activities (Free PDF Downloads)
A Detailed Guide to the ggplot Scatter Plot in R
A Detailed Guide to the ggplot Scatter Plot in R

Customizing Base R Plots

Base R allows for extensive customization using parameters like col for color, pch for point shape, and cex for point size. You can also add ablines or grid lines to the existing plot using separate functions like abline() or grid().

Method 2: Using the ggplot2 Package

If you are working in a professional or academic setting, ggplot2 is the tool you will likely reach for most often. Based on the Grammar of Graphics, it requires you to map your data to visual properties, known as aesthetics, resulting in highly flexible and consistent output.

AD

Installing and Loading ggplot2

Before you can use the package, you must install it from CRAN and load it into your R session. This one-time installation step ensures you have access to the latest functions and improvements.

Episode 17: 3 Ways to Amp-Up Your Scatter Plot! Featured Data Viz by Maarten Lambrechts — Data Viz Today
Episode 17: 3 Ways to Amp-Up Your Scatter Plot! Featured Data Viz by Maarten Lambrechts — Data Viz Today
3 Steps to Master Scatter Plots in the Classroom
3 Steps to Master Scatter Plots in the Classroom
a person holding a cell phone over a table with notes and pictures on it that read 11 activities for scatter plot graphs
a person holding a cell phone over a table with notes and pictures on it that read 11 activities for scatter plot graphs
A Detailed Guide to the ggplot Scatter Plot in R | R-bloggers
A Detailed Guide to the ggplot Scatter Plot in R | R-bloggers
How to create Beautiful, Interactive data visualizations using Plotly in R and Python?
How to create Beautiful, Interactive data visualizations using Plotly in R and Python?
How to make a plot with two different y-axis in R with ggplot2? (a secret ggplot2 hack)
How to make a plot with two different y-axis in R with ggplot2? (a secret ggplot2 hack)
  • install.packages("ggplot2")
  • library(ggplot2)

Building Your First ggplot

Constructing a plot in ggplot2 follows a specific structure: you start with the dataset and aesthetic mappings, followed by geometric layers. For a scatter plot, you use the geom_point() function to define the visual representation of the data points.

  • ggplot(data = your_data_frame) + geom_point(mapping = aes(x = var1, y = var2))

This syntax might feel verbose initially, but it pays off when you need to add elements like regression lines, change themes, or facet the data by categories.

AD

Adding Context and Polish

A great scatter plot is not just about the dots; it is about telling a clear story with your data. This involves adding descriptive labels for the axes and a title that immediately informs the reader about the visualization's purpose.

A ggplot2 Tutorial for Beautiful Plotting in R - Cédric Scherer
A ggplot2 Tutorial for Beautiful Plotting in R - Cédric Scherer
a diagram that shows how to use modeling
a diagram that shows how to use modeling
High School Scatter Plots: Correlation Worksheet
High School Scatter Plots: Correlation Worksheet
DataViz: How To Use Scatter Plots
DataViz: How To Use Scatter Plots
Teaching Scatterplots: Building Foundations for Data Analysis
Teaching Scatterplots: Building Foundations for Data Analysis
How to plot a violin scatter boxplot (in R)?
How to plot a violin scatter boxplot (in R)?
Simply creating various scatter plots with ggplot #rstats | R-bloggers
Simply creating various scatter plots with ggplot #rstats | R-bloggers
How to make a boxplot in R | R (for ecology)
How to make a boxplot in R | R (for ecology)
Create a Scatter Plot with Matplotlib
Create a Scatter Plot with Matplotlib
Anatomy of a Scatter Plot
Anatomy of a Scatter Plot
5 Free Online Scatter Plot Maker Tools To Look Out In 2021
5 Free Online Scatter Plot Maker Tools To Look Out In 2021
scatterplots and visualizing scatterplots are shown in this graphic
scatterplots and visualizing scatterplots are shown in this graphic
How to add 4 groups to make Categorical scatter plot with mean segments?
How to add 4 groups to make Categorical scatter plot with mean segments?
A ggplot2 Tutorial for Beautiful Plotting in R - Cédric Scherer
A ggplot2 Tutorial for Beautiful Plotting in R - Cédric Scherer
  • labs(title = "Your Title", x = "X Axis Label", y = "Y Axis Label")

Furthermore, modifying the visual theme can drastically improve readability. Functions like theme_minimal() or theme_classic() remove grid clutter, allowing the data to stand out more effectively.

Handling Data and Overplotting

When working with very large datasets, standard scatter plots can suffer from overplotting, where points overlap so much that individual observations become indistinguishable. This obscures the true density and pattern of the data.

AD

To mitigate this, you can adjust the transparency of the points using the alpha argument, which allows you to see areas of high concentration versus sparse regions. Alternatively, switching to a hexbin plot or a 2D density plot can provide a better aggregate view of the distribution.

Practical Example with Sample Data

To illustrate the concepts, let us create a scatter plot using the classic mtcars dataset that comes built into R. We will visualize the relationship between a car's weight (wt) and its miles per gallon (mpg).

Base R Example

The following code generates a base R plot with custom colors and labels.

  • plot(mtcars$wt, mtcars$mpg, main = "Car Weight vs. MPG", xlab = "Weight (1000 lbs)", ylab = "Miles Per Gallon", col = "steelblue", pch = 19)

ggplot2 Example

The equivalent code using ggplot2 demonstrates the layered grammar of graphics.

  • ggplot(mtcars, aes(x = wt, y = mpg)) +
      geom_point(color = "#2C7FB8", size = 3) +
      labs(title = "Car Weight vs. MPG", x = "Weight (1000 lbs)", y = "Miles Per Gallon") +
      theme_minimal()

By comparing these two approaches, you can choose the method that best fits your workflow, whether you prioritize speed of execution or the elegance of the final output.

AD