How to get rid of white space around ggplot2 map

866 Views Asked by At

How can I get rid of the white space around an image? Say that I have this code:

library(OpenStreetMap)
library(ggplot2)
library(maps)
library(tidyverse)
mp <- openmap(c(28,-115), c(50,-67),zoom=6,'stamen-watercolor')
states_map <- map_data("state") %>% filter(lat > 28 & lat < 50 & long > -115 & long < -67)
states_map_merc <- as.data.frame(projectMercator(states_map$lat,states_map$long))
states_map_merc$group <- states_map$group
counties_map <- map_data("county") %>% filter(lat > 28 & lat < 50 & long > -115 & long < -67)
counties_map_merc <- as.data.frame(projectMercator(counties_map$lat,counties_map$long))
counties_map_merc$group <- counties_map$group

a <- OpenStreetMap::autoplot.OpenStreetMap(mp,expand=FALSE) + 
    geom_polygon(data=states_map_merc, aes(x=x,y=y,group=group), fill="black",colour="white",alpha=0, size=.7) + 
    geom_polygon(data=counties_map_merc, aes(x=x,y=y,group=group), fill="black",colour="white",alpha=0, size=.2) +
    theme_void() +
    theme(plot.caption = element_text(size=11)) +
    geom_text(x=-10018754, y=3299499, label="Text.") +
    expand_limits(x=0, y=0) +
    scale_x_continuous(0) +
    scale_y_continuous(0)
ggsave(a, filename="map_static2.png")

This produces:

enter image description here

The white space bordering this map is undesirable. How can I get rid of it? In other words, I want to have the borders of the image be the tan edges of the map, not white space.

Note that this question relates to this one (How to make area saved with ggsave smaller). I tried what @MrFlick suggested by adding the expand_limits, scale_x_continuous, and scale_y_continuous lines, but they didn't seem to do anything.

UPDATE: Instead of the final four lines, I used:

scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) 
ggsave(a, filename="map_static3.png", width=8, height=4.64)

And it fixed it. The https://stackoverflow.com/a/22945857/2204410 link from @Jaap was it.

0

There are 0 best solutions below