R语言:为ggplot2绘图及图例添加矩形边框
Hey there! As someone new to R, it’s totally normal to hit snags with ggplot syntax—let’s work through your polygon plotting issue step by step. I notice your code cuts off mid-way through the scale_fill_manual call, which is likely one of the key problems. Here’s how to fix and debug this:
1. Fix the Incomplete scale_fill_manual Code
Your current code has a duplicate values=c( and is unfinished. This parameter needs a full set of colors mapped to your ALG categories. For example:
- If
ALGhas named categories (like "Good", "Fair", "Poor"), map each to a color explicitly:scale_fill_manual( "Aquatic Life Designated\nUse 2014 Assessment", values = c("Good" = "#2ecc71", "Fair" = "#f39c12", "Poor" = "#e74c3c") ) - If you just need to assign colors in the order of
ALG’s factor levels, use a simple vector:scale_fill_manual( "Aquatic Life Designated\nUse 2014 Assessment", values = c("#2ecc71", "#f39c12", "#e74c3c") )
2. Verify Your Data Format
Polygons in ggplot rely on properly structured data—double-check these details:
- Ensure
long,latare numeric columns (not character strings) in yourdfdata frame. - The
groupcolumn must correctly group all points that belong to the same polygon. If groups are misassigned, your shapes will render incorrectly or overlap. - Confirm
ALGis a categorical variable (convert it withdf$ALG <- factor(df$ALG)if it’s numeric) so ggplot can map colors to distinct groups.
3. Simplify to Test the Base Plot
Before adding titles and custom scales, test if the core polygon plot works:
# Minimal working example to check if polygons render graph1 <- ggplot() + geom_polygon(data = df, aes(x = long, y = lat, group = group, fill = ALG), colour = "black") + coord_equal() print(graph1)
If this basic plot shows up, you can safely add back your ggtitle, xlab, ylab, and fixed scale_fill_manual layer.
4. Troubleshoot Common Errors
- "Object not found": Double-check that all column names (
long,lat,group,ALG) match exactly what’s in yourdf(R is case-sensitive!). - Distorted/missing polygons: This usually means your
groupvariable is incorrect. Usetable(df$group)to check if each polygon has a unique group ID. - No fill colors showing: If
ALGis a continuous variable, usescale_fill_continuous()instead ofscale_fill_manual().
内容的提问来源于stack exchange,提问作者NBE

