Remove any space beyond the square with data

I have the general mtcars data as an example.

I create a quick geom_point() with two variables:

ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(size=2, shape=23)

enter image description here

What I want is to remove everything beyond the "gray-matrix" square.

For instance, I removed the axis, titles and ticks:

ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(size=2, shape=23) +
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

enter image description here

However, in this figure there is still a white area between the gray area and the external limit of the image.

This can be visualized in RStudio. In the next image I show the "white" margin that still persists in the plot:

enter image description here

My question, therefore, is how can I remove that white area beyond the gray square, so that the square takes full space?

>Solution :

Using theme_void

"A completely empty theme."

ggplot(data.frame(x = 0:4, y = 0:4), aes(x, y)) +
  geom_point(size = 2, shape = 23) +
  # "A completely empty theme."
  theme_void() +
  # set expansion to 0 to remove more white space
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  # check
  theme(panel.background = element_rect("yellow"))

enter image description here

Leave a Reply