You can use the title() function to quickly add a title to a plot in base R.
This function uses the following basic syntax:
#create scatterplot of x vs. y plot(df$x, df$y) #add title title('This is my title')
You can also use the following arguments in the title() function to customize the appearance of the title:
- col.main: The color of the title
- cex.main: The size of the title relative to the default size
- font.main: The font style to use for the title (1=plain, 2=bold, 3=italic, 4=bold italic)
- adj: The horizontal location of the title (0=left, 1=right, default is 0.5)
- line: The vertical location of the title (positive values move title up, negative values move title down)
The following example shows how to use the title() function in practice.
Example: How to Add Title to Plots in Base R
Suppose we use the plot() function in base R to create a simple scatterplot:
#create data frame df <- data.frame(x=c(70, 78, 90, 87, 84, 85, 91, 74, 83, 85), y=c(90, 88, 79, 86, 84, 83, 88, 92, 76, 75)) #create scatterplot of x vs. y plot(df$x, df$y, pch=16)
By default, base R does not add a title to the plot.
However, we can use the title() function to quickly add a title:
#create data frame df <- data.frame(x=c(70, 78, 90, 87, 84, 85, 91, 74, 83, 85), y=c(90, 88, 79, 86, 84, 83, 88, 92, 76, 75)) #create scatterplot of x vs. y plot(df$x, df$y, pch=16) #add title title('Plot of X vs. Y')
Notice that a title has been added to the plot.
We can customize the appearance of the title by using various arguments:
#create data frame df <- data.frame(x=c(70, 78, 90, 87, 84, 85, 91, 74, 83, 85), y=c(90, 88, 79, 86, 84, 83, 88, 92, 76, 75)) #create scatterplot of x vs. y plot(df$x, df$y, pch=16) #add title with custom appearance title('Plot of X vs. Y', col.main='blue', cex.main=2, font.main=4, adj=0, line=0)
Here is exactly what each argument did:
- col.main: Changed title font color to blue.
- cex.main: Increased title font to twice the default size.
- font.main: Changed title font style to italic.
- adj: Moved title all the way to the left.
- line: Moved title down to touch the top of the plot.
Feel free to play around with these various arguments in the title() function to create the exact title you’d like in your own plot.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
R: How to Use cex to Change the Size of Plot Elements
R: How to Use bty Option to Change Chart Box Styles
R: How to Change Legend Position in Plots