0

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.

bill999
  • 2,147
  • 8
  • 51
  • 103
  • 1
    Maybe this can help: https://stackoverflow.com/a/22945857/2204410 – Jaap May 24 '21 at 18:17
  • Your code produces a map unadorned by any frames. So that makes me think you're displaying the map via a web page or app. Given the map itself is frameless, that suggests that the frame - and whitespace - is being added by HTML or similar. So we need to see a reproducible example. This isn't one yet. – Limey May 24 '21 at 18:43
  • @Limey, I took a screenshot due to the file size limit of StackOverflow. That is why the image looks the way it does. The `ggsave` command produces the above image without the gray borders. Am I understanding your meaning? – bill999 May 24 '21 at 19:00
  • 1
    Yes. Your code produces a plot with no borders. Try it! – Limey May 24 '21 at 19:38
  • I tried it and it still had borders. But I modified it using the idea from @Jaaps answer and it works. See the solution in the question. Thanks for the help! – bill999 May 24 '21 at 20:30

0 Answers0