I am trying to create interactive Choropleth maps in R using leaflet package.
my final output should be like, when the user clicks any of the US state then a popup should be displayed with state name and the magnitude value for the corresponding state.
Below is the code that I am using. The issue I am facing is that, whenever I click on an any estate (except Alaska) the popup shows incorrect state name.
example if I click on the Florida state, the popup shows as Idaho.
Someone please explain what could be the potential issue that is causing this type of behavior.
library(rgdal)
library(leaflet)
us_states <- readOGR(dsn="cb_2016_us_state_500k.kml")
plot(us_states)
s <- read.csv("us_state_mag_values.csv")
popup1 <- paste0("<span style='color: #7f0000'><strong>us state values</strong></span>",
"<br><span style='color: salmon;'><strong>Stae: </strong></span>",
s$state,
"<br><span style='color: salmon;'><strong>relative amount: </strong></span>",
s$mag
)
palette <- colorBin(c('#fee0d2',
'#fcbba1',
'#fc9272',
'#fb6a4a',
'#ef3b2c',
'#cb181d',
'#a50f15',
'#67000d'),
bins = c(1,10,20,25,30,35,40,47))
mymap <- leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
addPolygons(data = us_states,
fillColor = ~palette(s$mag),
fillOpacity = 0.6,
color = "darkgrey",
weight = 1.5,
popup = popup1)%>%
addLegend(position = 'topleft',
colors = c('#fee0d2',
'#fcbba1',
'#fc9272',
'#fb6a4a',
'#ef3b2c',
'#cb181d',
'#a50f15',
'#67000d'),
labels = c('0%',"","","","","","",'100%'),
opacity = 0.6,
title = "relative<br>magnitude")
print(mymap)
the KML file can be found here
My dataset of US states and corresponding magnitude values look like this
EDIT
My Output visualization is pasted below. Notice the popup with incorrect state name.