Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 804
Bangyou Avatar asked Sep 05 '14 05:09

Bangyou


People also ask

How do I fix margins in ggplot2?

To remove the margins set all values to 0. Note that there is still space to fit all the elements of the plot. You can set negative values to reduce more the margins.

What does %>% mean in Ggplot?

1. the %>% is a pipe operator that is actually part of the dplyr library (along with the filter function) not from the ggplot2 library. To sample 1%, there is a sample_frac function in the dplyr library.

How do I get rid of the legend in ggplot2?

Example 1: Remove All Legends in ggplot2position = “none” within the theme options to get rid of both legends.

What is margin in R?

In R, the margin. table() function is used to compute the sum of table entries for a given index ( 1 for rows and 2 for columns).


1 Answers

(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))
like image 146
erc Avatar answered Oct 08 '22 05:10

erc