发散型调色板中0未映射为白色的技术求助
解决tmap发散调色板0值未显示白色的问题
我在使用tmap生成地图时,用了发散型调色板(如-RdBu),并将0设为breaks的分割点,但值为0的区域始终显示浅红色而非白色,尝试过其他发散调色板也存在同样问题。示例代码如下:
hom_trend_2019_2023 = (tm_shape(houston_zip) + tm_polygons(col="hom_change_2019_2023", border.alpha=0.1, palette="-RdBu", style="fixed", breaks=c(-Inf,-50,-40,-30,-20,-10,0,10,20,30,40,50,Inf), title="Change in Homicide Rate, 2019 to 2023 (Percent)") + tm_legend(bg.color="white", outside=TRUE, outside.size=0.15) + tm_shape(tx_hwys) + tm_lines(col="black")) tmap_save(hom_trend_2019_2023,"./plots/homicide_trend_2019_2023.png")
核心原因与解决方法
问题出在tmap默认不会自动将0值映射为发散调色板的中间色,即使breaks设置了0作为分割点。以下是两种有效解决方式:
1. 使用midpoint参数强制对齐中点
在tm_polygons中添加midpoint=0参数,这个参数专门用于发散调色板,会强制将调色板的中间色(比如RdBu的白色)映射到0值:
hom_trend_2019_2023 = (tm_shape(houston_zip) + tm_polygons(col="hom_change_2019_2023", border.alpha=0.1, palette="-RdBu", style="fixed", breaks=c(-Inf,-50,-40,-30,-20,-10,0,10,20,30,40,50,Inf), midpoint=0, # 指定中点为0 title="Change in Homicide Rate, 2019 to 2023 (Percent)") + tm_legend(bg.color="white", outside=TRUE, outside.size=0.15) + tm_shape(tx_hwys) + tm_lines(col="black")) tmap_save(hom_trend_2019_2023,"./plots/homicide_trend_2019_2023.png")
2. 手动创建对称调色板
如果自带调色板仍有问题,可以手动生成包含白色中点的对称调色板,确保颜色映射完全可控:
# 生成包含白色中点的12色发散调色板(对应13个breaks的12个区间) my_palette = colorRampPalette(c("darkred", "lightcoral", "white", "lightblue", "darkblue"))(12) hom_trend_2019_2023 = (tm_shape(houston_zip) + tm_polygons(col="hom_change_2019_2023", border.alpha=0.1, palette=my_palette, style="fixed", breaks=c(-Inf,-50,-40,-30,-20,-10,0,10,20,30,40,50,Inf), title="Change in Homicide Rate, 2019 to 2023 (Percent)") + tm_legend(bg.color="white", outside=TRUE, outside.size=0.15) + tm_shape(tx_hwys) + tm_lines(col="black"))
注意事项
- 确保breaks的正负区间数量对称(你的示例中从-50到0和0到50各有6个区间,符合要求),这样中点对齐后颜色分布会更协调。
- 对于
-RdBu这类反向调色板,midpoint参数同样生效,无需额外调整调色板方向。
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

