Leaflet多边形fillColor参数调用持续报错问题排查求助
Let's break down what's causing this error and how to fix it quickly:
The Root Cause
When you use st_sfc(df$shape) as the data argument in addPolygons, you're passing only the geometric component of your sf data frame, not the full dataset that includes your Low.Income.Card attribute. Leaflet's sf integration relies on having the entire sf object (geometry + attributes) to map style parameters like fillColor to the correct data values. Without that full context, it can't find the metadata needed to link your ~pal(Low.Income.Card) expression to the geometry, hence the confusing error.
The Fix
Instead of extracting just the geometry column, pass your complete df sf data frame to addPolygons. Here's the corrected line in your code:
m <- leaflet() %>% # addProviderTiles("CartoDB.DarkMatter") %>% # Uncomment if you want a base tile addPolygons(data = df, weight = 1, opacity = 1, color = "white", dashArray = "3", fillColor = ~pal(Low.Income.Card))
Why It Worked Without fillColor
When you remove the fillColor parameter, Leaflet only needs to render the geometry itself—no attribute data is required. That's why the standalone sfc object worked fine. But as soon as you try to style based on a data field, you need the full sf object to connect the dots between shapes and their corresponding values.
Quick Validation Check
Before running the corrected code, confirm df is still a valid sf object with:
class(df)
You should see output that includes sf (e.g., [1] "sf" "data.frame"). If not, recheck your left_join step to make sure you didn't accidentally drop the geometry column.
内容的提问来源于stack exchange,提问作者aStarIsCorn

