Bangyou
Bangyou

Reputation: 9816

How to remove the margin between plot region and panel in ggplot2?

I am creating some maps and want to remove all margins between the plot region and panel border.

This is the minimal example to reproduce my question

library(ggplot2)
library(grid)
df <- expand.grid(list(x = seq(1, 10), y = seq(1, 10), z = seq(1, 2)))

p <- ggplot(df) + geom_tile(aes(x, y)) + facet_wrap(~z)

p <- p + theme_minimal() + xlab('') + ylab('')
p <- p + theme(axis.text = element_blank(),
    panel.grid = element_blank(),
    axis.ticks = element_blank(),
    panel.border = element_rect(colour = 'black', fill = 'transparent'),
    panel.margin = unit(0, 'mm'))
p + ylim(2, 6) + xlim(2, 6)

This is the result of my codes.

enter image description here

How could I remove all white areas in the figure above? Thanks for any suggestions.

Upvotes: 19

Views: 7889

Answers (1)

erc
erc

Reputation: 10131

(Alright, here's my comment as an answer..)

Just add the following to the plot:

+ scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

Upvotes: 27

Related Questions