如何在 ggplot2 中的多边形上叠加点?

How to overlay points on polygons in ggplot2?

我正在努力在显示不同人口普查区平均家庭收入的形状文件上绘制城市空间点数据框。 我的收入数据是从 CDPHE Open Data for Colorado 下载的,我使用的是地图包中提供的城市数据。我特别需要使用 ggplot2 来可视化数据。我通读了类似的问题并修改了其他答案的代码,但仍然无法理解。

下面是我尝试编写代码的一种方法:

library(ggplot2)
library(maps)
library(sp)
library(raster)
library(spdplyr)

incp_prj <- shapefile("Income_Poverty_(Census_Tracts).shp")

data(us.cities)
coords <- cbind(us.cities$long, us.cities$lat)
us.cities <- SpatialPointsDataFrame(coords = coords, data = us.cities, proj = incp_prj@proj4string)
co.cities <- us.cities %>% filter(country.etc == "CO")

pt_data = as.data.frame(incp_prj)
grid_data = as.data.frame(co.cities)

ggplot(grid_data, aes(x = long, y = lat)) + geom_tile(aes(fill = incp_prj$Poverty_Me)) + 
                            geom_point(data = pt_data)

其中returns错误:

Aesthetics must be either length 1 or the same as the data (21): fill

有兴趣下载我的具体收入数据的可以找here.

阅读 R graph gallery 中的更多示例后,我终于明白了!我需要将有关贫困的数字信息合并到多边形数据框中,即使它们是相同的空间对象。

如果有人感兴趣,这里是绘制多边形上的点的代码:

library(ggplot2)
library(maps)
library(sp)
library(raster)
library(spdplyr)
library(broom)
library(mapproj)
library(viridis)

#Read in shape file and pull cities from {maps} package
incp_prj <- shapefile("Income_Poverty_(Census_Tracts).shp")

data(us.cities)
coords <- cbind(us.cities$long, us.cities$lat)
us.cities <- SpatialPointsDataFrame(coords = coords, data = us.cities, proj = incp_prj@proj4string)
co.cities <- us.cities %>% filter(country.etc == "CO")
grid_data = as.data.frame(co.cities)

#Fortify data to put into a dataframe that ggplot can use
spdf_fortified <- tidy(incp_prj, region = "OBJECTID") 

#coerce x and y IDs to match
incp_prj %>% mutate(`OBJECTID`= as.character(`OBJECTID`))

#Combine numerical data(income) with the polygons
graph <- spdf_fortified %>%
  left_join(. , incp_prj %>% mutate(`OBJECTID`= as.character(`OBJECTID`)), by = c("id"="OBJECTID"), copy = TRUE)

#Plot
ggplot() +
  geom_polygon(data = graph, aes(fill = Poverty_Me, x = long, y = lat, group = group)) +
  theme_void() +
   scale_fill_viridis(trans = "log", name="Income (USD)", guide = guide_legend( keyheight = unit(3, units = "mm"), keywidth=unit(12, units = "mm"), label.position = "bottom", title.position = 'top', nrow=1) ) +
  labs(title = "Average Household Income and Major Cities in Colorado") +
  theme(
    text = element_text(color = "#22211d"),
    plot.background = element_rect(fill = "#f5f5f2", color = NA),
    panel.background = element_rect(fill = "#f5f5f2", color = NA),
    legend.background = element_rect(fill = "#f5f5f2", color = NA),

    plot.title = element_text(size= 16, hjust=0.01, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
    legend.position = c(0.7, 0.09)) +
  coord_map()+
#Add the city points
  geom_point(data = grid_data, aes(x = grid_data$long, y = grid_data$lat), size = 3, 
        shape = 23, fill = "orange")

产生了这个: