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 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 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))
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
Additional Resources
How to Remove Gridlines in ggplot2
How to Set Axis Limits in ggplot2
How to Change Legend Position in ggplot2