In this article, we will discuss how to change the background color of a ggplot2 plot in R Programming Language.
To do so first we will create a basic ggplot2 plot.
Step 1: Create sample data for the plot.
sample_data <- data.frame(x = 1:10, y = 1:10)
Step 2: Load the package ggplot2.
library("ggplot2")
Step 3: Draw a basic ggplot2 plot without any color customization.
ggplot(sample_data, aes(x, y)) + geom_point()
R
library ( "ggplot2" )
sample_data <- data.frame (x = 1:10, y = 1:10)
ggplot (sample_data, aes (x, y)) + geom_point ()
|
Output:

Basic ggplot2 plot
Changing the color of the background panel
We will use the argument panel.background of ggplot2 to change the background color of panel of plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(panel.background = element_rect(fill = “#00ab75”)
R
library ( "ggplot2" )
sample_data <- data.frame (x = 1:10, y = 1:10)
ggplot (sample_data, aes (x, y)) +
geom_point ()+
theme (panel.background = element_rect (fill = "#00ab75" ))
|
Output:

Plot with panel background color green
Changing the color of the plot in ggplot2
We will use the argument plot.background of ggplot2 to change the background color of the plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(plot.background = element_rect(fill = “#00ab75”))
R
library ( "ggplot2" )
sample_data <- data.frame (x = 1:10, y = 1:10)
ggplot (sample_data, aes (x, y)) +
geom_point ()+
theme (plot.background = element_rect (fill = "#00ab75" ))
|
Output:

Plot with background color green
Changing the overall theme of the plot in ggplot2
We have some pre-built themes in ggplot2 that can be used to change the complete theme in ggplot2. Themes available in ggplot are,
- theme_gray
- theme_bw
- theme_linedraw
- theme_light
- theme_dark
- theme_minimal
- theme_classic
- theme_void
- theme_test
Syntax:
ggplot(sample_data, aes(x, y)) + geom_point()+ theme_dark()
R
library ( "ggplot2" )
sample_data <- data.frame (x = 1:10, y = 1:10)
ggplot (sample_data, aes (x, y)) + geom_point ()+ theme_dark ()
|
Output:

Plot with dark theme in ggplot2