Axis titles are important for the clarity of a graph. They give the reader information about the variables which are represented and their unit (if any). A common mistake is to omit the unit, thus leading to misinterpretation of the data and aberrant conclusions. Axis titles should be clear, short but descriptive enough to leave no doubt about the variables.
In ggplot2, there are several ways to assign a title to an axis, and to change its look. Here we will see a couple of them using a simple example.
Let’s see that with the scatter plot below. This plot is the result by the following code and is stored in the object baseplot
so that we can reuse it throughout the whole tutorial:
baseplot <- ggplot(df, aes(values1, values2)) +
geom_point(size=2)
baseplot
As you may see here, ggplot()
has already taken care of placing the variable names (i.e. values1
and values2
) as axis titles. The whole point here is to override this action by default, and replace values1
by variable1 (unit)
, and values2
by variable2 (unit)
.
Here we use the functions xlab()
and ylab()
to add the new titles to the axes:
baseplot +
xlab("variable1 (unit)") +
ylab("variable2 (unit)")
The functions scale_x_continuous()
and scale_y_continuous()
(alternatively scale_x_discrete()
and scale_y_discrete()
if your variables are discrete instead of continuous) may be use instead of xlab()
and ylab()
:
baseplot +
scale_x_continuous("variable3 (unit)") +
scale_y_continuous("variable4 (unit)")
If you wish to change the size and/or color of the axis titles, you won’t be able to do it using the previous functions. Instead, you will have to modify the theme of the plot itself. To do so, you will have to add an additional line to the code and use the function theme(axis.title = element_text())
:
baseplot +
xlab("variable1 (unit)") +
ylab("variable2 (unit)") +
theme(axis.title = element_text(color = "blue", size = 12))
You can alternatively modify only one of the axis titles, or both in a different manner, by replacing axis.title
with axis.title.x
and/or axis.title.y
:
baseplot +
xlab("variable1 (unit)") +
ylab("variable2 (unit)") +
theme(axis.title.x = element_text(color = "blue", face ="bold", size = 12)) +
theme(axis.title.y = element_text(color = "red", size = 14))