You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot scale_colour_stepsn设置分级地图自定义标签时遇报错

解决scale_fill_stepsn中breaks与labels长度不匹配的报错

报错原因

你指定了5种颜色,这需要划分5个区间,每个区间由两个相邻的分隔点(breaks)定义,因此breaks的数量必须是颜色数+1(即6个)。你之前仅设置了5个breaks,ggplot会自动补充边界值(如-Inf和Inf),导致breaks长度变为6,而你设置的labels长度仍为5,两者不匹配,触发报错。

修正代码

直接使用scale_fill_stepsn(无需用scale_colour_stepsn再指定aesthetics="fill"),调整breaks数量为6个,并通过guide_colorsteps自定义区间标签:

my_colours <- c("#00B050", "#92D050", "#FFFFB2", "#FED976", "#FEB24C")
aus_shp <- read_sf("~/map files/STE_2016_AUST.shp")
aus_shp$ent_gentob <- c(4.3,11.9,8.3,6.1,14.5,0.0,16.8,4.6,NA)

ggplot(data = aus_shp) +
  geom_sf(aes(fill = ent_gentob))+
  theme_void()+
  theme(legend.position = c(.93, .93),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        legend.margin = margin(6, 6, 6, 6))+
  scale_fill_stepsn(
    colours =  my_colours,
    breaks = c(0, 1, 5, 10, 15, 20), # 6个分隔点对应5个区间
    limits = c(0, 20), # 限定数值范围,避免自动补充Inf
    name = "% R",
    guide = guide_colorsteps(
      labels = c("≤1%", "1-<5%", "5-<10%", "10-<15%", "15-≤20%"),
      ticks = FALSE # 关闭分隔点刻度,仅显示区间标签
    )
  )

复用比例尺的方法

将自定义比例尺封装成函数,后续画图直接调用即可:

# 定义复用的比例尺函数
my_custom_fill_scale <- function() {
  scale_fill_stepsn(
    colours = c("#00B050", "#92D050", "#FFFFB2", "#FED976", "#FEB24C"),
    breaks = c(0, 1, 5, 10, 15, 20),
    limits = c(0, 20),
    name = "% R",
    guide = guide_colorsteps(
      labels = c("≤1%", "1-<5%", "5-<10%", "10-<15%", "15-≤20%"),
      ticks = FALSE
    )
  )
}

# 调用示例
ggplot(data = aus_shp) +
  geom_sf(aes(fill = ent_gentob))+
  theme_void()+
  theme(legend.position = c(.93, .93),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        legend.margin = margin(6, 6, 6, 6))+
  my_custom_fill_scale()

内容的提问来源于stack exchange,提问作者missanita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:55:06