[英]How can I create a heatmap on a map using only zipcodes
我有下面的 dataframe,我想知道我是否可以僅使用郵政編碼在芝加哥 map 上繪制熱圖。 Count
將用作數值。
structure(list(Zip = structure(c(15L, 19L, 25L, 27L, 30L, 30L,
41L), .Label = c("60411", "60415", "60462", "60607", "60608",
"60609", "60610", "60612", "60613", "60614", "60615", "60616",
"60617", "60618", "60619", "60620", "60621", "60622", "60623",
"60624", "60625", "60626", "60628", "60629", "60630", "60631",
"60632", "60633", "60634", "60636", "60637", "60638", "60639",
"60640", "60641", "60642", "60643", "60644", "60645", "60646",
"60647", "60649", "60651", "60652", "60653", "60655", "60656",
"60657", "60659", "60660", "60707"), class = "factor"), Count = c(2L,
2L, 2L, 2L, 2L, 2L, 2L)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -7L), groups = structure(list(
Zip = structure(c(15L, 19L, 25L, 27L, 30L, 41L), .Label = c("60411",
"60415", "60462", "60607", "60608", "60609", "60610", "60612",
"60613", "60614", "60615", "60616", "60617", "60618", "60619",
"60620", "60621", "60622", "60623", "60624", "60625", "60626",
"60628", "60629", "60630", "60631", "60632", "60633", "60634",
"60636", "60637", "60638", "60639", "60640", "60641", "60642",
"60643", "60644", "60645", "60646", "60647", "60649", "60651",
"60652", "60653", "60655", "60656", "60657", "60659", "60660",
"60707"), class = "factor"), .rows = structure(list(1L, 2L,3L, 4L, 5:6, 7L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))
您需要 zip 代碼和地理空間邊界之間的映射。 這是一個選項:
下載芝加哥 Z4348F938BDDDD8475E967CCB47ECB234Z 邊界的形狀文件。 保存文件並解壓; 我假設相關文件位於 R 工作文件夾的根目錄下。
假設您的data.frame
帶有計數和 ZIP 代碼稱為data
,讀取形狀文件並通過左連接添加計數。
library(rgdal) # Make sure the name of the shape file matches the name of the shape file # from the ZIP archive shp <- readOGR("geo_export_4e602fd1-be14-4590-8a68-fdbca198af8f.shp") # Add count data library(dplyr) shp@data <- shp@data %>% left_join(data, by = c("zip" = "Zip"))
示例 plot 使用leaflet
。
library(leaflet) pal <- colorNumeric("Reds", domain = NULL) leaflet(shp) %>% addPolygons( color = "black", weight = 1, fillColor = ~ pal(Count))
要添加圖例,我建議先從Count
列中刪除NA
。
library(dplyr)
library(tidyr)
shp@data <- shp@data %>%
left_join(data, by = c("zip" = "Zip")) %>%
replace_na(list(Count = 0))
然后使用addLegend
添加顏色圖例
library(leaflet)
pal <- colorNumeric("Reds", domain = NULL)
leaflet(shp) %>%
addPolygons(
color = "black",
weight = 1,
fillColor = ~ pal(Count)) %>%
addLegend(
"bottomright",
pal = pal,
values = ~ Count,
title = "Count",
opacity = 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.