plot(mtcars$disp, mtcars$mpg)
In this chapter, we will learn how to create scatter plots.
Let us recreate the plot that we had created in Chapter 2 by using the mtcars data set. We will use the disp (displacement) and mpg (miles per gallon) variables. disp will be on the X axis and mpg will be on the Y axis.
We have created a very basic plot and any one looking at it for the first time will get confused with the axis labels mtcars$disp and mtcars$mpg. Let us put into practice what we learnt in Chapter 3, and add a title to the plot, and make the axis labels more meaningful.
plot(mtcars$disp, mtcars$mpg,
main = 'Displacement vs Miles Per Gallon',
xlab = 'Displacement', ylab = 'Miles Per Gallon')
Now the plot clearly communicates that it represents the relationship between the displacement and mileage of cars. Now the color of the points in the plot is black by default. Some of us may agree that black is beautiful but not all of us will like it. As a first step in enhancing the way our plot looks, let us change the shape of the points.
The shape of the point can be specified using the pch argument. It will take values between 0 and 25. Below is an example:
Let us check out a few of the other shapes:
We can specify the shape based on a third (categorical variable as well). In the below plot, the shape is based on the levels of the categorical variable cyl (number of cylinders) from the mtcars data set. Note that nlevels(factor(mtcars$cyl)) returns a single value (3), so it would give every point the same shape β instead, map each observation to its own level with as.numeric(factor(...)):
The size of the points in the scatter plot can be specified using the cex argument in the plot() function. The default value for cex is 1.
The below plots show the size of the points for values relative to 1.
We can specify a border color for the points using the col argument and a background color using the bg argument. The background color can be specified only for points whose pch argument takes values between 21 and 25. Let us look at some examples to understand this distinction between border and background color.
You can observe that although we have specified a background color using the bg argument, we do not see the red background color as the value specified for the pch (shape) argument is not between 21 and 25. In the next example, we will use a value between 21 and 25 so that the pch argument is effective.
The color of the points can be specified using (levels) of a categorical variable as well. In the next example, we will use the cyl variable to specify the color of the points.
# color based on a third variable
plot(mtcars$disp, mtcars$mpg, pch = 5, col = as.numeric(factor(mtcars$cyl)))
Since cyl is a categorical variable with 3 levels, we can see that the points now have 3 different colors. The above method is useful when you want to segregate the points in a scatter plot based on a third variable.
Try it in your browser. Edit the code below and press Run β it executes entirely in your browser via WebR, so no R installation is needed. The runtime downloads once, on this page only. The printed plots are produced in your browser and are not part of the PDF or ePub editions.
---
description: "Base R scatter plots with plot(): control point shape with pch, size with cex, colour with col and bg, and map a third variable to shape or colour."
---
# Scatter Plots {#scatter}
## Introduction
In this chapter, we will learn how to create scatter plots.
- adding color to the points
- modify shape of the points
- modify size of the points
## Basic Plot
Let us recreate the plot that we had created in Chapter 2 by using the `mtcars` data set. We will use the `disp` (displacement) and `mpg` (miles per gallon) variables. `disp` will be on the X axis and `mpg` will be on the Y axis.
```{r}
plot(mtcars$disp, mtcars$mpg)
```
We have created a very basic plot and any one looking at it for the first time will get confused with the axis labels `mtcars$disp` and `mtcars$mpg`. Let us put into practice what we learnt in Chapter 3, and add a title to the plot, and make the axis labels more meaningful.
```{r}
plot(mtcars$disp, mtcars$mpg,
main = 'Displacement vs Miles Per Gallon',
xlab = 'Displacement', ylab = 'Miles Per Gallon')
```
Now the plot clearly communicates that it represents the relationship between the displacement and mileage of cars. Now the color of the points in the plot is black by default. Some of us may agree that black is beautiful but not all of us will like it. As a first step in enhancing the way our plot looks, let us change the shape of the points.
## Shape
The shape of the point can be specified using the `pch` argument. It will take values between **0** and **25**. Below is an example:
```{r}
# point shape
plot(mtcars$disp, mtcars$mpg, pch = 6)
```
Let us check out a few of the other shapes:
```{r, echo=FALSE, fig.align='center', fig.width=10, fig.height=10}
#| label: fig-scatter-pch
#| fig-cap: "The pch argument across the plotting symbols"
#| fig-alt: "A grid of 25 scatterplots of displacement against miles per gallon, all drawing identical points. Each panel shows one plotting symbol in turn, from the open circle of pch 1 through the filled circle, triangle, square and cross, numbered by pch value in a blue label at the top."
init <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
values <- c(4, 10, 16, 22)
for (i in values) {
plot(mtcars$disp, mtcars$mpg, pch = i, cex = 1.5)
mtext(paste("pch = ", i), side = 3, col = "blue")
}
par(init)
```
We can specify the shape based on a third (categorical variable as well). In the below plot, the shape is based on the levels of the categorical variable `cyl` (number of cylinders) from the `mtcars` data set. Note that `nlevels(factor(mtcars$cyl))` returns a single value (`3`), so it would give every point the same shape β instead, map each observation to its own level with `as.numeric(factor(...))`:
```{r}
#| label: fig-scatter-factor
#| fig-cap: "Mapping a third variable to point shape using as.numeric(factor())"
#| fig-alt: "A scatterplot of displacement against miles per gallon in which the points take three different open-circle-to-triangle shapes according to the number of cylinders. A legend at the top right labels the three groups 4 cyl, 6 cyl and 8 cyl. The four-cylinder points cluster at the top left, the eight-cylinder points at the right and bottom."
# shape based on a third categorical variable
plot(mtcars$disp, mtcars$mpg, pch = as.numeric(factor(mtcars$cyl)))
legend('topright', legend = c('4 cyl', '6 cyl', '8 cyl'), pch = 1:3)
```
## Size
The size of the points in the scatter plot can be specified using the `cex` argument in the `plot()` function. The default value for `cex` is 1.
```{r}
# point size
plot(mtcars$disp, mtcars$mpg, cex = 1.5)
```
The below plots show the size of the points for values relative to 1.
```{r, echo=FALSE, fig.align='center', fig.width=10, fig.height=10}
#| label: fig-scatter-cex
#| fig-cap: "The cex argument across a range of point sizes"
#| fig-alt: "A grid of nine scatterplots of displacement against miles per gallon drawing identical points, each panel showing the same symbol at a progressively larger size, from a tiny cross in the first panel to a large filled circle in the last."
# different point sizes
init <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
values <- c(0.5, 1, 1.5, 2)
for (i in values) {
plot(mtcars$disp, mtcars$mpg, pch = 6, cex = i)
mtext(paste("cex = ", i), side = 3, col = "blue")
}
par(init)
```
## Color
We can specify a border color for the points using the `col` argument and a background color using the `bg` argument. The background color can be specified only for points whose `pch` argument takes values between **21** and **25**. Let us look at some examples to understand this distinction between border and background color.
```{r}
# shape between 0 and 21
plot(mtcars$disp, mtcars$mpg, pch = 5, col = 'blue', bg = 'red')
```
You can observe that although we have specified a background color using the `bg` argument, we do not see the red background color as the value specified for the `pch` (shape) argument is not between 21 and 25. In the next example, we will use a value between 21 and 25 so that the `pch` argument is effective.
```{r}
# shape between 22 and 25
plot(mtcars$disp, mtcars$mpg, pch = 24, col = 'red', bg = 'blue')
```
The color of the points can be specified using (levels) of a categorical variable as well. In the next example, we will use the `cyl` variable to specify the color of the points.
```{r}
#| label: fig-scatter-two-vars
#| fig-cap: "Two variables mapped at once: shape to cylinders, colour to transmission"
#| fig-alt: "A scatterplot of displacement against miles per gallon combining both mappings. Point shape encodes the cylinder count and point colour encodes transmission, with a legend at the top right showing the three cylinder shapes."
# color based on a third variable
plot(mtcars$disp, mtcars$mpg, pch = 5, col = as.numeric(factor(mtcars$cyl)))
```
Since `cyl` is a categorical variable with 3 levels, we can see that the points now have 3 different colors. The above method is useful when you want to segregate the points in a scatter plot based on a third variable.
## Try it live {.unnumbered}
> **Try it in your browser.** Edit the code below and press **Run** -- it
> executes entirely in your browser via
> [WebR](https://docs.r-wasm.org/webr/latest/), so no R installation is
> needed. The runtime downloads once, on this page only. The printed plots
> are produced in your browser and are not part of the PDF or ePub editions.
```{webr-r}
# combine shape, size and color from this chapter
plot(mtcars$disp, mtcars$mpg,
pch = as.numeric(factor(mtcars$cyl)),
cex = mtcars$wt * 4,
col = as.numeric(factor(mtcars$am)))
legend("topright", legend = c("4 cyl", "6 cyl", "8 cyl"), pch = 1:3)
```