使用ggplot绘制带数值网格的地图时出现线条交叉异常求助
Hey Danilo, sorry to hear you're stuck with those weird line crossings in your grid map—let's walk through the most common fixes for this issue!
1. First, Check for Topological Errors in Your Shapefile
Line crossings often stem from broken topology in your spatial data. Here's how to diagnose and fix it:
- Validate your spatial object: Use the
rgeospackage to check if your shapefile has invalid geometries:
If this returns a message like "Self-intersection", you've found the culprit.library(rgeos) gIsValid(your_spatial_data, reason = TRUE) - Fix invalid geometries: A quick fix for most self-crossing issues is to use
gBuffer()with a 0-width buffer—it essentially "heals" broken polygons:fixed_spatial_data <- gBuffer(your_spatial_data, width = 0, byid = TRUE)
2. Switch to the sf Package for Smoother Spatial Handling
Your current script uses sp, but the newer sf package has better topological support and plays nicer with ggplot2. Try converting your spatial data to sf format:
library(sf) # Convert sp object to sf sf_grid <- st_as_sf(your_spatial_data) # Merge with your value dataframe (make sure you have a matching ID column!) merged_sf <- dplyr::left_join(sf_grid, your_dataframe, by = "grid_id") # Plot with geom_sf() ggplot(merged_sf) + geom_sf(aes(fill = your_value_column)) + viridis::scale_fill_viridis() + coord_sf()
geom_sf() automatically handles polygon grouping, so it avoids the line crossing issues that can pop up with geom_polygon() and sp objects.
3. Verify Your Data Matching & Grouping
If you're sticking with sp and geom_polygon, double-check that you're grouping polygons correctly. Missing or incorrect grouping will make ggplot connect points across different grids, causing crossings:
# Convert sp object to a dataframe for ggplot grid_df <- fortify(your_spatial_data, region = "grid_id") # Merge with your value data merged_df <- dplyr::left_join(grid_df, your_dataframe, by = c("id" = "grid_id")) # Plot with explicit group parameter ggplot(merged_df) + geom_polygon(aes(x = long, y = lat, group = id, fill = your_value_column)) + viridis::scale_fill_viridis() + coord_fixed()
The group = id line is critical here—it tells ggplot to draw each grid square as a separate polygon, not connect all points into one messy shape.
4. Rule Out Grid Generation Issues
If you created the grid yourself (instead of using a pre-made shapefile), check your grid generation code:
- If using
st_make_grid, ensure thecellsizeparameter is set correctly and isn't creating overlapping grid cells. - If using
spsample+Polygon, verify that each grid cell's coordinates are correctly ordered (polygons need to be defined clockwise or counter-clockwise without crossing paths).
Quick Cleanup Tip
You have duplicate library loads (sp, raster) in your script—while it's not causing the line issue, cleaning those up can avoid potential package conflict headaches down the line!
内容的提问来源于stack exchange,提问作者Danilo Carvalho

