根据邮政编码创建传单地图

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

我有下面的数据框:

mapd<-structure(list(City = c("Henderson", "Henderson", "Los Angeles", 
"Fort Lauderdale", "Fort Lauderdale", "Los Angeles", "Los Angeles", 
"Los Angeles", "Los Angeles", "Los Angeles"), State = c("Kentucky", 
"Kentucky", "California", "Florida", "Florida", "California", 
"California", "California", "California", "California"), Zip = c(42420, 
42420, 90036, 33311, 33311, 90032, 90032, 90032, 90032, 90032
), Sales = c(261.96, 731.94, 14.62, 957.5775, 22.368, 48.86, 
7.28, 907.152, 18.504, 114.9)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

我想创建一个

leaflet
地图,通过标记显示
Sales
和城市。我想我需要使用 shapefile 数据来完成此操作并遵循如下逻辑,但我对以下事实感到困惑:我不知道在哪里可以找到我们的 shapefile,而且我没有纬度和经度数据。:

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(mapd, by = c("zip" = "Zip"))
Example plot using leaflet.

library(leaflet)
leaflet(shp) 
leaflet(data = shp) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.numeric(Sales), label = ~as.character(City))
r r-leaflet
1个回答
3
投票

这里有一个使用

zipcodeR
的选项(如果您不需要用多边形显示城市范围)。您可以使用
geocode_zip
获取每个邮政编码的纬度和经度,然后将
lat
long
数据加入到原始数据框中,然后使用
leaflet

library(zipcodeR)
library(leaflet)
library(tidyverse)

mapd %>%
  left_join(.,
            geocode_zip(mapd$Zip) %>% mutate(zipcode = as.numeric(zipcode)),
            by = c("Zip" = "zipcode")) %>%
  leaflet() %>%
  addTiles() %>%
  addMarkers(
    ~ lng,
    ~ lat,
    popup = ~ as.character(Sales),
    label = ~ as.character(City)
  )

输出

enter image description here

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