简体   繁体   中英

Cropping a map made with geom_polygon

I am creating a map using geom_polygon :

## libraries
library(tidyverse)

## render map
map_data("state") %>% 
  ggplot(mapping = aes(x = long, y = lat, group = group)) +
  geom_polygon(color = "gray") +
  coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_blank())

The map renders correctly, however, as you will see, there is a ton of white space on either side of the map:

在此处输入图像描述

Is there anyway to automatically crop the map so as shown below?

在此处输入图像描述

You need to add limits to your coord_map call.

map_data("state") %>% 
  ggplot(mapping = aes(x = long, y = lat, group = group)) +
  geom_polygon(color = "gray") +
  coord_map(projection = "albers", lat0 = 39, lat1 = 45,
            xlim = c(-117,-75), ylim = c(26,49)) +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_blank())

Then make sure your graphics device has dimensions that match your plot:

ggsave("~/temp.png",width = 1.55 * 5, height = 5)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM