关于R语言中地图/Shapefile网格识别与着色的技术咨询
Hey there! Let's work through your two questions about grid map handling in R—these are really common tasks, so I'll break down practical, actionable solutions for you.
First, if you're using rasterToPolygons to generate your grid, each cell is essentially a spatial polygon object. Switching to the sf package (the modern standard for spatial data in R) will make identifying and filtering cells much easier, since each row in your sf data frame represents one grid cell, with built-in geometry and attribute columns.
Step 1: Identify Your Grid Cells
When you convert a raster to polygons (or load a pre-made grid Shapefile), you can add a unique ID to each cell to make identification straightforward. For example:
library(sf) library(raster) library(dplyr) # Example: Create a sample raster and convert to sf grid sample_raster <- raster(nrow = 15, ncol = 15, xmn = 0, xmx = 15, ymn = 0, ymx = 15) values(sample_raster) <- 1:225 # Convert to sf format and add a unique grid ID grid_sf <- st_as_sf(rasterToPolygons(sample_raster)) %>% mutate(grid_id = row_number()) # View the first few rows to confirm IDs and attributes head(grid_sf)
Each row here corresponds to one grid cell, with grid_id giving you a unique reference for each.
Step 2: Omit Specific Cells
To remove cells, just filter the sf data frame using your chosen criteria—whether that's by ID, spatial location, or even attribute values:
# Omit cells by specific IDs filtered_grid <- grid_sf %>% filter(!grid_id %in% c(10, 25, 42, 67)) # Exclude these IDs # Or omit cells outside a specific spatial boundary # First create a polygon for the area you want to keep keep_area <- st_polygon(list(rbind(c(2,2), c(12,2), c(12,12), c(2,12), c(2,2)))) %>% st_sfc(crs = st_crs(grid_sf)) # Filter cells that intersect with the keep area filtered_grid <- grid_sf %>% st_filter(keep_area, .predicate = st_intersects) # Plot to check the result plot(st_geometry(filtered_grid), main = "Grid with Selected Cells Removed")
The key here is linking your custom data to the grid using a shared identifier (like the grid_id we added earlier). Once they're joined, you can use ggplot2 (for flexible, polished plots) or base R plotting to color the cells.
Step 1: Prepare & Join Your Data
First, make sure your custom data frame has a column that matches the grid's identifier (e.g., grid_id):
# Example custom data frame my_custom_data <- tibble( grid_id = 1:225, metric_value = runif(225, min = 0, max = 100) # Replace with your actual data ) # Join the data to the grid grid_with_data <- grid_sf %>% left_join(my_custom_data, by = "grid_id")
Step 2: Color the Grid
Using ggplot2 gives you full control over colors, labels, and styling:
library(ggplot2) ggplot(grid_with_data) + geom_sf(aes(fill = metric_value), color = "white", size = 0.1) + # White cell borders scale_fill_viridis_c(option = "magma", name = "My Custom Metric") + # Nice color scale theme_minimal() + labs(title = "Grid Colored by Custom Data") + theme(axis.text = element_blank(), axis.title = element_blank()) # Clean up axes
If you prefer base R plotting, you can do this too:
plot(grid_with_data["metric_value"], key.pos = 1, main = "Grid Colored by Custom Data", pal = viridis::viridis(10)) # Use viridis for colorblind-friendly scales
A Quick Note on Your intersect Concerns
If you're having issues with intersect (from the old sp package), switching to sf::st_intersection() will likely resolve things. The sf package handles spatial operations more consistently and preserves attribute data better, which makes post-processing (like filtering and coloring) much smoother.
内容的提问来源于stack exchange,提问作者Danilo Carvalho

