How to Make a Scatter Plot in R: Easy Step-by-Step Guide
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.
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.
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.
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.
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.
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.
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.
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.