The themes layer is used to style all the non-data ink of the plot, i.e., all the visual elements that are not part of data.
When we create a chart using ggplot2, it automatically uses a default theme. For theming we have a few choices:
Use the default theme (What we have seen so far). The default theme is called theme_grey().
Use a built-in theme. There are two built-in themes 1) theme_grey() which is default and 2) theme_bw(), a theme with a white background.
Modify/override specific elements of the default theme. This is done by using the theme() function. It overrides the graphical parameters of the default theme.
Create your own theme
Use the Default Theme
The following chart is created using the default theme:
ggplot - Chart with built-in black and white theme
Modify/Override specific elements of the chosen theme
We can use the default theme or another built-in theme and then override some elements of it using the theme() function.
The visual elements can be classified as one of the three different types:
Text
Line
Rectangle
Each type can be modified by calling the appropriate function, namely, element_text(), element_line() and element_rect().
Let's take a few examples to understand how this works.
Change Plot Background to Light Yellow
By default, the entire plot has a white background. We will change to to light green color. The background color of the plot is defined by plot.background() in the default function. The background is a part of the rectangle shape, so we can modify it using the element_rect() function. We will change the background color to light yellow and add a gray border of size 2.
The plot lines can be modified using the element_line() function. Take a look at the default theme function above. The axis lines are axis.line and axis ticks are defined with axis.ticks. Also notice that the panels have a grid which is defined by panel.grid. We will remove the grids by using element_blank().
This way we can modify almost every element of the ggplot and achieve any kind of styling we want.
Continue Reading
Premium Content
This tutorial is a part of the course Data Visualization with R. This is a premium course. The purchase options for the course are provided below. With this course, you get access to complete course content, source code, practical exercises, and all resources that are a part of the course.
Lifetime Premium Membership
$250
$179
Get unlimited access to all courses and premium content