How to Change Background Color in ggplot2 (With Examples)

To change the background color in ggplot2, use the theme() function and specify the element_rect() argument to the fill argument. By setting this argument to a hex code or a color name, you can change the background color of a ggplot2 plot. You can also use the scale_fill_manual() function to manually adjust the background color of a graph. Examples of both of these methods are provided in the ggplot2 documentation.


You can use the following syntax to change the background color of various elements in a ggplot2 plot:

p + theme(panel.background = element_rect(fill = 'lightblue', color = 'purple'),
          panel.grid.major = element_line(color = 'red', linetype = 'dotted'),
          panel.grid.minor = element_line(color = 'green', size = 2))

Alternatively, you can use built-in ggplot2 themes to automatically change the background color. Here are some of the more commonly used themes:

p + theme_bw() #white background and grey gridlines
p + theme_minimal() #no background annotations
p + theme_classic() #axis lines but no gridlines

The following examples show how to use this syntax in practice.

Example 1: Specify Custom Background Color

The following code shows how to create a basic scatterplot in ggplot2 with the default grey background:

library(ggplot2)

#create data frame
df <- data.frame(x=c(1, 3, 3, 4, 5, 5, 6, 9, 12, 15),
                 y=c(13, 14, 14, 12, 17, 21, 22, 28, 30, 31))

#create scatterplot
p <- ggplot(df, aes(x=x, y=y)) +
       geom_point()

#display scatterplot
p

We can use the following code to change the background color of the panel along with the major and minor gridlines:

p + theme(panel.background = element_rect(fill = 'lightblue', color = 'purple'),
          panel.grid.major = element_line(color = 'red', linetype = 'dotted'),
          panel.grid.minor = element_line(color = 'green', size = 2))

Change background color in ggplot2

Example 2: Use Built-in Theme to Change Background Color

The following code shows how to use various built-in ggplot2 themes to automatically change the background color of the plots:

p + theme_bw() #white background and grey gridlines

p + theme_minimal() #no background annotations

p + theme_classic() #axis lines but no gridlines

x