How To Modify the Margins in ggplot2 (With Examples)

The margins of a ggplot2 plot can be easily modified using the margin() function. This function takes four arguments – top, right, bottom and left – which specify the margin widths in clockwise order from the top. By default, ggplot2 uses a margin of 0.1 for each side. The margin() function can be used in the ggplot() function to modify the margin widths. Example code is provided to illustrate how this works.


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.

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

x