【问题标题】:Compare cities by area in ggplot2 on map在地图上的 ggplot2 中按区域比较城市
【发布时间】:2018-12-19 10:48:50
【问题描述】:

我需要在 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()

【问题讨论】:

    标签: r ggplot2 maps coordinates facet-wrap


    【解决方案1】:

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

    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")
    

    【讨论】:

    • 太棒了。凌乱不是问题。你真是天才!所以,还有一个问题。请问您知道,我可以通过坐标计算这些城市的面积并按面积大小排列城市吗?
    • 我确信可以做到,但如果没有进一步的研究,我不确定如何做到。可能值得在这里单独提出一个问题。
    【解决方案2】:

    这有点棘手,因为您需要每个面板都有“可用”空间,但不能将其与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)
    

    【讨论】:

    • 在第二个版本中,它们的大小都是一样的,不幸的是(
    • 是的,我会删除它。但是第一个选项它们的大小不一样。
    • 是的,谢谢,您的代码很容易理解!我想我会使用 Photoshop 将所有城市放在情节的中心。
    猜你喜欢
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多