ggplot2中scale_fill_stepsn函数颜色不匹配问题求助
问题原因及解决方案
你遇到的问题是因为scale_fill_stepsn默认会对指定的colors做线性插值渐变,而不是直接给每个断点区间分配单一固定颜色。它会在你设置的breaks(0-1、1-10、10-100)之间生成过渡色,所以地图上的颜色和scales::show_col展示的单一色块不符。
下面提供两种解决思路:
方法1:直接给区间分配固定颜色(推荐)
将连续的rate变量切割为离散分组,再用scale_fill_manual指定每个分组的颜色,完全匹配你想要的色块:
# 先给rate变量按断点分组 rate$rate_group <- cut(rate$rate, breaks = c(0, 1, 10, 100, Inf), # 包含大于100的数值 labels = c("0-1", "1-10", "10-100", ">100"), include.lowest = TRUE) # 包含0这个最小值 # 绘制地图 ggplot(data = rate) + geom_sf(aes(fill = rate_group)) + theme_bw() + scale_fill_manual(name = "Test Rate \n (n/1000)", values = c("#999999","#6666FF", "#FFFF66","#FF6633"), limits = levels(rate$rate_group)) + annotation_north_arrow(location = "tl", which_north = "true", pad_x = unit(0.1, "in"), pad_y = unit(0.05, "in"), height = unit(1, "cm"), width = unit(1, "cm"), style = north_arrow_fancy_orienteering) + annotation_scale(location = "bl", width_hint = 0.2)
方法2:保留scale_fill_stepsn但关闭渐变过渡
如果你想继续使用scale_fill_stepsn,可以通过设置参数让颜色在断点处直接跳变,而非渐变:
ggplot(data = rate) + geom_sf(aes(fill = rate)) + theme_bw() + scale_fill_stepsn(name = "Test Rate \n (n/1000)", # 将断点归一化到0-1范围,对应颜色位置 values = c(0, 1, 10, 100) / max(rate$rate, na.rm = TRUE), colors = c("#999999","#6666FF", "#FFFF66","#FF6633"), breaks = c(0,1, 10, 100), labels=scales::label_number(accuracy=1), show.limits = TRUE, # 关闭图例的等间距显示,匹配实际断点区间 guide = guide_colorsteps(even.steps = FALSE)) + annotation_north_arrow(location = "tl", which_north = "true", pad_x = unit(0.1, "in"), pad_y = unit(0.05, "in"), height = unit(1, "cm"), width = unit(1, "cm"), style = north_arrow_fancy_orienteering) + annotation_scale(location = "bl", width_hint = 0.2)
内容的提问来源于stack exchange,提问作者ay__ya
相关产品推荐
相关产品推荐

