SF shapefile数据框与外部tibble连接报错及绘图问题求助
Hey there! Let's break down these two problems you're facing with your shapefile and data joins step by step.
1. Fixing the "object 'Gemeente' not found" Error
Even if you swear the column names and types match, there are a few sneaky culprits that often cause this error when joining sf objects with external data:
Hidden whitespace or special characters: Sometimes column values look identical but have trailing/leading spaces or invisible characters. Clean both columns first:
# Trim whitespace and standardize case to avoid mismatches shp_df$Gemeente <- trimws(tolower(shp_df$Gemeente)) example_df$Gemeente <- trimws(tolower(example_df$Gemeente))Column name truncation: Old shapefiles sometimes truncate long column names (e.g., to 10 characters). Double-check the actual column names in your sf object:
# List all columns in the shapefile's attribute table colnames(st_drop_geometry(shp_df))If the column name got truncated (e.g.,
Gemeentinstead ofGemeente), adjust your joinbyparameter to match the truncated name.Explicitly specify the join key: Don't rely on auto-matching—always define the
byparameter clearly when joining. For example, usingdplyr:joined_sf <- dplyr::left_join(shp_df, example_df, by = "Gemeente")Verify data frame visibility: Make sure both
shp_dfandexample_dfare in your current working environment. Runls()to confirm they're listed.
2. Troubleshooting Partial Plotting Issues
Since you didn't detail exactly what "异常" looks like, here are the most common fixes for wonky partial plots with sf data:
Ensure your joined data is still a valid sf object: Joins can sometimes accidentally drop the geometry column. Check the class first:
class(joined_sf) # If it's not "sf", convert it back: joined_sf <- st_as_sf(joined_sf)Filter out NA values: If some municipalities in
example_dfdon't match the shapefile, you'll get NA rows. Filter these before plotting:filtered_sf <- joined_sf %>% filter(!is.na(geometry)) plot(filtered_sf["your_data_column"]) # Replace with your target columnCheck your plotting syntax: If using
ggplot2, make sure you're usinggeom_sf()correctly (don't mix up with regulargeom_polygon):library(ggplot2) ggplot(filtered_sf) + geom_sf(aes(fill = your_data_column)) + theme_minimal()Validate your subset logic: If you're plotting a subset of municipalities, double-check your filter condition. For example:
# Test with a small, known subset test_sf <- shp_df %>% filter(Gemeente %in% c("Amsterdam", "Rotterdam")) plot(test_sf)If this works, your filter for the full dataset might have a typo or incorrect logic.
内容的提问来源于stack exchange,提问作者Tdebeus

