如何为ggmap中的gemo_polygon数据添加图例?附绘图背景
Got it, let's figure out how to add a legend for your geom_polygon layers in ggmap—since you're working with manta ray detection and tagging data, this should fit right into your existing plot setup. Here's a straightforward, actionable breakdown:
Key Background First
To get a legend for geom_polygon, you need to map a categorical variable (like polygon group/type) to either the fill or color aesthetic inside aes(). ggplot will automatically generate a legend based on this mapping.
Step-by-Step Implementation
Let's assume you have a polygon dataset (let's call it manta_polygons) that defines regions relevant to your MR/MRTag data (e.g., detection hotspots, tagging zones). First, add a category column to this polygon data to distinguish different polygon groups (e.g., "MR Detection Zones" vs "MRTag Tagging Zones").
Then, integrate it into your ggmap code like this:
# Load required packages library(ggmap) library(ggplot2) # Example polygon data (replace with your actual polygon coordinates) manta_polygons <- data.frame( Longitude = c(71.2, 71.4, 71.4, 71.2, 71.6, 72.0, 72.0, 71.6), Latitude = c(-6.7, -6.7, -6.5, -6.5, -5.5, -5.5, -5.3, -5.3), Polygon_Type = rep(c("MR Detection Regions", "MRTag Tagging Regions"), each = 4) ) # Get your base map (adjust location/zoom to match your data) base_map <- get_map(location = c(lon = 71.5, lat = -6), zoom = 10, maptype = "terrain") # Build the full plot with legend for polygons ggmap(base_map) + # Add MR detection points geom_point(data = MR, aes(x = Longitude, y = Latitude), color = "navy", size = 2, alpha = 0.6) + # Add MRTag tagging points geom_point(data = MRTag, aes(x = deploy_lon, y = deploy_lat), color = "darkred", size = 3, shape = 17) + # Add polygons WITH legend mapping geom_polygon(data = manta_polygons, aes(x = Longitude, y = Latitude, fill = Polygon_Type), alpha = 0.3, # Keep transparent to avoid hiding points/map color = "black") + # Customize the legend appearance scale_fill_manual( name = "Polygon Categories", # Legend title values = c("MR Detection Regions" = "lightblue", "MRTag Tagging Regions" = "pink") ) + # Add plot labels labs( x = "Longitude", y = "Latitude", title = "Manta Ray Observations & Tagging Zones" ) + theme_bw()
Critical Notes
- If you only have one polygon type, create a dummy categorical column (e.g.,
Polygon_Type = rep("Manta Ray Habitat", nrow(your_polygon_data))) to force ggplot to generate a legend. - Use
colorinstead offillinaes()if you want the legend to represent polygon outline colors instead of fill colors. - Adjust
alphato ensure your polygons don't block the underlying map or points.
内容的提问来源于stack exchange,提问作者mikejwilliamson

