如何用R的tm_polygons实现含0中点的正负值Jenks分类地图
解决方案
你的需求是固定区间分类,而非Jenks自动分类(Jenks会自动计算最优分界,无法匹配你指定的精确区间),所以需要改用style = "fixed",手动定义断点和对应配色。
步骤1:定义自定义断点与配色
根据你指定的区间,先设置精确的断点(注意tm_polygons的fixed样式默认左闭右开,要调整断点确保0单独成类),再匹配对应的颜色:
- 红色系用从深到浅的红,0用白色,蓝色系用从浅到深的蓝(可根据喜好调整色值)
完整修改后的代码
# 自定义断点(左闭右开,确保0单独区间) custom_breaks <- c(-50, -21, -10, -1, 0, 1, 10, 30, 70) # 对应配色:3个红色 + 白色 + 3个蓝色 custom_palette <- c("#c41e3a", "#e05263", "#f7a0ad", "#ffffff", "#63a0f7", "#3a7bc4", "#1e46c4") # 自定义图例标签,匹配你的区间描述 custom_labels <- c("-50至-21", "-20至-10", "-9至-1", "0", "1至10", "11至30", "50至70") tm_shape(df_name %>% filter(ANO == 2012), bbox = bbox_new) + tm_polygons(col = "tot_reloc_net_05", style = "fixed", # 启用固定区间 breaks = custom_breaks, palette = custom_palette, title = "", labels = custom_labels) + # 替换图例标签 tm_layout(main.title = "", main.title.position = "center", frame = F, main.title.size = 1.5, fontfamily = "serif", fontface = "bold", legend.width = 0.40, legend.outside = F, legend.position = c(0.75, 0.25), legend.text.size = 0.5, legend.title.size = 1.0) + tm_shape(df_shape_1) + tm_borders(lwd = 1.85, col = "black") + tm_text("MA", xmod = -1.25, ymod = -0.995, size = 0.6) + tm_shape(df_shape_2) + tm_borders(lwd = 0.5, col = "black") + tm_compass(type = "arrow", position = c("right", "bottom"), size = 1.35) + tm_scale_bar(text.size = 0.45, position = c("right", "bottom"), width = 0.18)
注意事项
- 如果数据中有超出
-50或70的数值,需要在断点首尾添加-Inf和Inf,比如custom_breaks <- c(-Inf, -50, -21, -10, -1, 0, 1, 10, 30, 70, Inf),同时对应调整配色和标签数量 - 色值可以自行替换,比如用
RColorBrewer的预设色系:brewer.pal(3, "Reds")取红色,brewer.pal(3, "Blues")取蓝色,中间加白色即可
内容的提问来源于stack exchange,提问作者msc
相关产品推荐
相关产品推荐

