I have the dataframe below:
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"))
and I want to create a leaflet
map that will display the Sales
and City via markers. I guess that I need to use shapefiles data for us to do this and follow the logic like below but Im confused by the fact that I do not know where to find us shapefiles and also that I do not have latitude and longitude 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(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))
Here is an option using zipcodeR
(if you don't need to show the city extents with a polygon). You can get the latitude and longitude for each zipcode using geocode_zip
, then join the lat
and long
data to your original dataframe, then use 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)
)
Output