How to Modify the Margins in ggplot2 (With Examples)


You can use the theme() argument in ggplot2 to change the margin areas of a plot:

ggplot(df, aes(x=x)) + 
  geom_histogram() +
  theme(plot.margin=unit(c(5,1,1,1), 'cm'))

Keep in mind that the order for the plot margins is:

  • unit(c(top, right, bottom, left), units)

The following examples shows how change the margin areas of ggplot2 plots in practice.

Example 1: Create Basic Plot

The following code shows how to create a basic plot in ggplot2 without specifying any margin areas:

library(ggplot2)

#make this example reproducible
set.seed(0)

#create data
df <- data.frame(x=rnorm(n=5000))

#create histogram using ggplot2
ggplot(df, aes(x=x)) + 
  geom_histogram() +
  ggtitle('Title of Histogram') +
  theme(plot.background=element_rect(fill='#e3fbff'))

Notice how the plot has minimal margins on each side.

Example 2: Modify Margins of the Plot

The following code shows how to add significant margins to the top and bottom of the plot:

library(ggplot2)

#make this example reproducible
set.seed(0)

#create data
df <- data.frame(x=rnorm(n=5000))

#create histogram with significant margins on top and bottom
ggplot(df, aes(x=x)) + 
  geom_histogram() +
  ggtitle('Title of Histogram') +
  theme(plot.margin=unit(c(5,1,5,1), 'cm'),
        plot.background=element_rect(fill='#e3fbff'))

Notice how there’s a significant amount of space on the top and bottom of the plot.

And the following code shows how to add significant margins to the left and right of the plot:

library(ggplot2)

#make this example reproducible
set.seed(0)

#create data
df <- data.frame(x=rnorm(n=5000))

#create histogram with significant margins on left and right
ggplot(df, aes(x=x)) + 
  geom_histogram() +
  ggtitle('Title of Histogram') +
  theme(plot.margin=unit(c(1,5,1,5), 'cm'),
        plot.background=element_rect(fill='#e3fbff'))

ggplot2 plot with margins

Notice how there’s a significant amount of space on the left and right of the plot.

Additional Resources

The following tutorials explain how to perform other common operations in ggplot2:

How to Change Font Size in ggplot2
How to Rotate Axis Labels in ggplot2
How to Remove a Legend in ggplot2
How to Remove Axis Labels in ggplot2

Leave a Reply

Your email address will not be published.