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

Using GGPlot to plot spatial data and color based on a column value in R

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

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

请注意,我知道下面的代码不起作用,但它说明了我凭直觉试图完成的事情

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

谢谢!

确保您的 csv 具有与 shapefile 相同的行数和相同的区域,并且顺序相同。 cbind population 列从 csv 到 shapefile 属性。然后你就用geom_polygon一次,fill=population是一个额外的aes(除了x,y,group)。

如果行不匹配,您可以使用 dplyr::join 来获取人口列。