How to add a second y axis in R

In this tutorial, we will see how to plot a second y axis in R. To do that, we need to superpose two plots and to add the second y axis outside the plot function.

Normal scatterplot (above) and scatterplot with a second y axis (below) produced in R

Load the dataset

data("iris")

Variables assignment

dataset = iris
x_column = "Sepal.Width"
y1_column = "Sepal.Length"
y2_column = "Petal.Length"

Change the margin sizes

par(mar = c(5, 4, 4, 4) + 0.3)

Plot a second y axis in R

Arguments for the axis (to add an axis to a plot) and mtext (to add an axis label to a plot) functions:

  • side = 1 to add a bottom axis
  • side = 2 to add a left axis
  • side = 3 to add a top axis
  • side = 4 to add a right axis
plot(dataset[, x_column], dataset[, y1_column], pch = 18, col = "black",
     xlim = c(0, max(dataset[, x_column])),
     ylim = c(0, max(dataset[, y1_column])),
     xlab = x_column, ylab = y1_column,
     cex = 1.5, cex.lab = 1.5, cex.axis = 1.5)

par(new = TRUE)

plot(dataset[, x_column], dataset[, y2_column], pch = 18, col = "red",
     xlim = c(0, max(dataset[, x_column])),
     ylim = c(0, max(dataset[, y2_column])),
     xlab = "", ylab = "",
     cex = 1.5, axes = FALSE)
axis(side = 4, cex.axis = 1.5, col.axis = "red")
mtext(y2_column, side = 4, line = "3", cex = 1.5, col = "red")

This code was adapted from an issue on StackOverFlow.

Scatterplot with a second y axis produced in R

Reset the margin sizes to default values

par(mar = c(5.1, 4.1, 4.1, 2.1))

Conclusion

In conclusion, it is absolutely possible to plot two different y axes in base R. Have you found what you were looking for?

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply