Add Borders Around Entire ggplot2 Plot in R

Viewed 1928

I want to draw a border around an entire ggplot2 plot, such as the box("figure") function would do in case of a Base R plot.

Have a look at the following example:

data <- data.frame(x = 1:5,
                   y = 1:5)

library("ggplot2")

ggplot(data, aes(x, y)) +
  geom_point()

enter image description here

I would like to add a border around this plot as shown below:

enter image description here

I cannot believe that this information doesn't exist anywhere. Unfortunately, all I find is how to add a panel border.

How could I add a border around the ENTIRE ggplot2 plot?

1 Answers

The theme element plot.background is an element_rect, which normally has a color of NA. Just change this to whatever color you like and adjust the size to control the line width.

ggplot(data, aes(x, y)) +
  geom_point() +
  theme(plot.background = element_rect(color = "deepskyblue3", size = 3))

enter image description here

Related