使用GGPlot根据R中的列值绘制空间数据和颜色

问题描述 投票:0回答:1

Im从shapefile中读取空间数据,该文件包含一个省中100个地区的位置。在另一个数据框中,我有每个地区的人口数据。

我正在尝试使用ggplot来创建省的地图(来自shapefile),并根据人口规模为每个地区着色。这里的问题是我不知道如何填写shapefile所获得的地图,其颜色基于包含在另一个数据框中的区域对应的人口值的颜色。

请注意,我理解下面的代码不起作用,但是它说明了Im凭直觉试图完成的工作

districts_from_shapefile <- readOGR("districts.shp")
districts_with_pop <- read.csv(file = "districts_populations.csv")

ggplot() +  
        geom_polygon(data=districts_from_shapefile, aes(x=long,y=lat,group=group)) +
        geom_polygon(data=districts_with_pop, aes(fill=districts_with_pop$population))

谢谢!

r ggplot2 data-science shapefile sf
1个回答
1
投票

请确保您的csv与shapefile具有相同的行数和相同的区域,并且顺序相同。将人口列从csv绑定到shapefile属性。然后,您只需使用一次geom_polygon,并且fill = population是一个额外的aes(x,y,group除外)。

如果行不匹配,则可以使用dplyr :: join替换人口列。

© www.soinside.com 2019 - 2024. All rights reserved.