Leaflet coloring the wrong polygon

My reprex. Run as is, it colors "Ellis" county instead of "El Paso" county. Ellis is adjacent to El Paso alphabetically. If I uncomment the other counties, they all get filled perfectly, but El Paso and Ellis still swap color fill. I am totally mystified.

library(tidyverse)
library(leaflet)

#   Get county outlines
USA <- raster::getData("GADM", country = "usa", level = 2)

Texas <- USA[USA@data$NAME_1 == "Texas", ]

init_zoom <- 6
MapCenter <- c(-99.9018, 31.9686) # center of state

TodayData <- tribble(
    ~County,    ~Cases,       ~Population, ~percapita,
#  "Bell",         1,       342236,     0.292,
#  "Bexar",        4,      1925865,     0.208,
#  "Bowie",        1,        93858,     1.07,
#  "Brazoria",     2,       353999,     0.565,
#  "Brazos",       1,       219193,     0.456,
#  "Collin",       6,       944350,     0.635,
#  "Dallas",      15,      2586552,     0.580,
#  "Denton",       4,       807047,     0.496,
  "El Paso",      3,       837654,     0.358
#  "Fort Bend",    9,       739342,     1.22,
#  "Galveston",    2,       327089,     0.611,
#  "Gregg",        1,       123494,     0.810,
#  "Harris",      10,      4602523,     0.217,
#  "Hays",         1,       204150,     0.490,
#  "Lavaca",       1,        19941,     5.01,
#  "Matagorda",    1,        36743,     2.72,
#  "Medina",       1,        49334,     2.03,
#  "Montgomery",   3,       554445,     0.541,
#  "Rusk",         1,        53595,     1.87,
#  "Smith",        5,       225015,     2.22,
#  "Tarrant",      5,      2019977,     0.248,
#  "Travis",       4,      1203166,     0.332,
#  "Webb",         1,       272053,     0.368
)

temp <-  merge(Texas, TodayData,
              by.x = c("NAME_2"), by.y = c("County"),
              all.x = TRUE) 

palcase <- colorNumeric(
  na.color = "transparent",
  palette = rev(heat.colors(8)),
  domain = temp$Cases)

leaflet(TodayData) %>% 
  setView(lng = MapCenter[1] , lat = MapCenter[2], zoom = init_zoom ) %>%   
  addTiles() %>%
  addPolygons(data = Texas, 
              stroke = TRUE,
              weight = 1,
              smoothFactor = 0.2, 
              fillOpacity = 0.5,
              label = ~NAME_2,
              fillColor = ~palcase(temp$Cases))

Solved it. Should be

addPolygons(data = temp,

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.