Chapter 14 Themes
14.1 Introduction
In this final chapter, we will learn to modify the appearance of all non data components of the plot such as:
- axis
- legend
- panel
- plot area
- background
- margin
- facets
14.2 Basic Plot
We will continue with the scatter plot examining the relationship between displacement and miles per gallon from the the mtcars data set.
<- ggplot(mtcars) +
p geom_point(aes(disp, mpg))
p
14.3 Axis
14.3.1 Text
The axis.title.x
argument can be used to modify the appearance of the X
axis. In the below example, we modify the color and size of the title using
the element_text()
function. Remember, whenever you are trying to modify the
appearance of a theme element which is a text, you must use element_text()
.
You can use axis.title.y
to modify the Y
axis title and to modify the
title of both the axis together, use axis.title
.
+ theme(axis.title.x = element_text(color = "red", size = 10, face = "italic")) p
14.3.2 Ticks
To modify the appearance of the axis ticks, use the axis.ticks
argument. You can
change the color, size, linetype and length of the ticks using the element_line()
function as shown below.
+ theme(axis.ticks = element_line(color = 'blue', size = 1.25, linetype = 2),
p axis.ticks.length = unit(1, "cm"))
14.4 Legend
Now, let us look at modifying the non-data components of a legend.
<- ggplot(mtcars) +
p geom_point(aes(disp, mpg, color = factor(cyl), shape = factor(gear)))
p
14.4.1 Background
The background of the legend can be modified using the legend.background
argument. You can change the background color, the border color and line type
using element_rect()
.
+ theme(legend.background = element_rect(fill = 'gray', linetype = 3,
p color = "black"))
14.4.2 Text
The appearance of the text can be modified using the legend.text
argument.
You can change the color, size and font using the element_text()
function.
+ theme(legend.text = element_text(color = 'green', face = 'italic')) p