You're looking for the title() function in base R.
While the preferred way is to include xlab and ylab in your initial plot() command, if you've already plotted and don't want to re-run the entire plotting sequence (especially if you've added other elements like lines, points, or text using lines(), points(), text(), etc.), title() will modify the labels of the current plot.
Here's how to use it:
# 1. Simulate your initial plot without labels
my_x <- 1:10
my_y <- my_x^2
plot(my_x, my_y) # This plot currently has no axis labels
# 2. Now, add the axis labels using title()
title(xlab = "My X-axis Label", ylab = "My Y-axis Label")
# You can also add a main title, sub-title, etc., with title()
# title(main = "My Awesome Plot", xlab = "Time (seconds)", ylab = "Distance (meters)", sub = "Data from Experiment 1")
Explanation:
title(): A function that adds/modifies the main title, subtitles, and axis labels to the current plot.
xlab: Argument for the label of the x-axis.
ylab: Argument for the label of the y-axis.
Important Considerations:
- If you haven't added anything else: If your plot is just the basic
plot(x, y) and you haven't added other layers, it's often simpler to just re-run your plot() command with xlab and ylab included:
# Simpler way if no other layers are added
plot(my_x, my_y, xlab = "My X-axis Label", ylab = "My Y-axis Label")
mtext() for more control: For very specific placement of text in the margins (including mimicking axis labels), you could also use mtext(), but title() is generally more direct for standard axis labels. mtext() gives you more control over position (side, line) but is more verbose for this specific task.
# Alternative using mtext (more advanced for labels)
# plot(my_x, my_y, ann = FALSE) # Suppress default annotations if you use mtext
# mtext("X Axis Label", side = 1, line = 3) # side 1 = bottom
# mtext("Y Axis Label", side = 2, line = 3) # side 2 = left