在地图上的 ggplot2 中按区域比较城市

Compare cities by area in ggplot2 on map

我需要在 ggplot2 中按地区比较乌克兰城市。 但是它们都以相同的大小绘制。

你能帮帮我吗?

我使用这个代码:

library(ggplot2)

cities <- read.csv("https://raw.githubusercontent.com/savchukidze/maps/master/cities.csv", stringsAsFactors = F)


png("compare_cities.png", height = 3000, width = 2500)

ggplot()+

   geom_polygon(data = cities, aes(long, lat, group = group), 
                color = "black", size = 2.5, fill = "grey", alpha = 1)+
   facet_wrap(~city, scales = "free")

dev.off()

这有点棘手,因为您需要每个面板都有 "free" space,但不能将其与 coord_fixed 组合。

您需要将它们全部放在比例尺上以获得坐标。

library(tidyverse)
cities %>% 
    group_by(city) %>% 
    mutate(long=long-mean(long), lat=lat-mean(lat)) %>% 
    ggplot(aes(long, lat, group=city)) + 
        geom_polygon() + 
        facet_wrap(~city)

有点乱,但是你可以像这样在每个城市的最大范围内绘制不可见点,以保持比例相同...

library(tidyverse)
ranges <- cities %>% 
  group_by(city) %>% 
  summarise(minlat=min(lat),              #get limits for each city
            maxlat=max(lat),
            minlon=min(long),
            maxlon=max(long)) %>% 
  mutate(rangelat=maxlat-minlat,          #calculate range required for each
         rangelon=maxlon-minlon,
         centrelat=(maxlat+minlat)/2,     #calculate centre point of plot
         centrelon=(maxlon+minlon)/2) %>% 
  ungroup() %>% 
  mutate(bottom=centrelat-max(rangelat)/2,#calculate box size based on max range
         top=centrelat+max(rangelat)/2,
         left=centrelon-max(rangelon)/2,
         right=centrelon+max(rangelon)/2)

ggplot()+
  geom_polygon(data = cities, aes(long, lat, group = group), 
               color = "black", size = 2.5, fill = "grey", alpha = 1)+
  geom_point(data=ranges, aes(x=left,y=bottom), alpha=0)+ #invisible bottom left point
  geom_point(data=ranges, aes(x=right,y=top),alpha=0)+    #invisible top right point
  facet_wrap(~city,scales = "free")