Open In App

How to change background color in R using ggplot2?

Last Updated : 04 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# load ggplot2
library("ggplot2")
  
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
  
# Draw plot with ggplot2
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




# load ggplot2
library("ggplot2")
  
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
  
# Draw plot with changed theme using 
# panel.background parameter
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




# load ggplot2
library("ggplot2")
  
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
  
# Draw plot with changed theme using 
# plot.background parameter
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




# load ggplot2
library("ggplot2")
  
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
  
# Draw plot with changed theme using 
# different prebuilt themes
ggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()


Output:

Plot with dark theme in ggplot2



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads