1 import shutil, os
   2 os.makedirs('_utils', exist_ok=True)
   3 for f in ['plot_utils.py', 'china_provinces.geojson']:
   4     src = os.path.join(os.path.dirname(__file__), f)
   5     if os.path.exists(src):
   6         shutil.copy2(src, f'_utils/{f}')
   7 
   8 import numpy as np
   9 import matplotlib.pyplot as plt
  10 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
  11 setup_style()
  12 
  13 import geopandas as gpd
  14 from libpysal.weights import Queen
  15 from esda.moran import Moran_Local
  16 
  17 gdf = gpd.read_file('_utils/china_provinces.geojson')
  18 
  19 # 模拟有空间自相关的数据
  20 np.random.seed(42)
  21 gdf['centroid_x'] = gdf.geometry.centroid.x
  22 gdf['value'] = 0.3 + 0.005 * (gdf['centroid_x'] - 80) + np.random.randn(len(gdf)) * 0.08
  23 gdf['value'] = gdf['value'].clip(0.1, 0.95)
  24 
  25 # 构建空间权重 + 计算 LISA
  26 w = Queen.from_dataframe(gdf, use_index=False)
  27 w.transform = 'r'
  28 lisa = Moran_Local(gdf['value'].values, w, permutations=999)
  29 
  30 # LISA 聚类分类
  31 # lisa.q: 1=HH, 2=LH, 3=LL, 4=HL
  32 # lisa.p_sim: p 值
  33 sig_level = 0.05
  34 gdf['lisa_cluster'] = 'NS'
  35 for i in range(len(gdf)):
  36     if lisa.p_sim[i] <= sig_level:
  37         q = lisa.q[i]
  38         if q == 1: gdf.loc[gdf.index[i], 'lisa_cluster'] = 'HH'
  39         elif q == 2: gdf.loc[gdf.index[i], 'lisa_cluster'] = 'LH'
  40         elif q == 3: gdf.loc[gdf.index[i], 'lisa_cluster'] = 'LL'
  41         elif q == 4: gdf.loc[gdf.index[i], 'lisa_cluster'] = 'HL'
  42 
  43 cluster_colors = {
  44     'HH': '#E25B5B',  # 热点(红色)
  45     'LL': '#5B8DB8',  # 冷点(蓝色)
  46     'LH': '#A8C4D8',  # 低高异常(浅蓝)
  47     'HL': '#E0A0A0',  # 高低异常(浅红)
  48     'NS': '#F0F0F0',  # 不显著(灰色)
  49 }
  50 
  51 from collections import Counter
  52 counts = Counter(gdf['lisa_cluster'])
  53 
  54 # === 画图 ===
  55 fig, ax = plt.subplots(figsize=(10, 8))
  56 
  57 for cluster_type in ['NS', 'HL', 'LH', 'LL', 'HH']:  # NS 先画,显著的后画
  58     subset = gdf[gdf['lisa_cluster'] == cluster_type]
  59     if len(subset) > 0:
  60         subset.plot(color=cluster_colors[cluster_type], edgecolor='white',
  61                     linewidth=0.5, ax=ax, zorder=2 if cluster_type != 'NS' else 1)
  62 
  63 # 省份简称标注(只标注显著的)
  64 provinces_short = {
  65     '北京市':'北京','天津市':'天津','河北省':'河北','山西省':'山西',
  66     '内蒙古自治区':'内蒙古','辽宁省':'辽宁','吉林省':'吉林','黑龙江省':'黑龙江',
  67     '上海市':'上海','江苏省':'江苏','浙江省':'浙江','安徽省':'安徽',
  68     '福建省':'福建','江西省':'江西','山东省':'山东','河南省':'河南',
  69     '湖北省':'湖北','湖南省':'湖南','广东省':'广东','广西壮族自治区':'广西',
  70     '海南省':'海南','重庆市':'重庆','四川省':'四川','贵州省':'贵州',
  71     '云南省':'云南','西藏自治区':'西藏','陕西省':'陕西','甘肃省':'甘肃',
  72     '青海省':'青海','宁夏回族自治区':'宁夏','新疆维吾尔自治区':'新疆',
  73     '台湾省':'台湾','香港特别行政区':'香港','澳门特别行政区':'澳门',
  74 }
  75 
  76 for _, row in gdf[gdf['lisa_cluster'] != 'NS'].iterrows():
  77     c = row.geometry.centroid
  78     short = provinces_short.get(row['name'], row['name'][:2])
  79     # ★ 统一用不透明白底 bbox + 深色文字
  80     ax.text(c.x, c.y, short, ha='center', va='center', fontsize=6.5,
  81             fontweight='bold', color='#333333',
  82             bbox=dict(boxstyle='round,pad=0.15', facecolor='white',
  83                       edgecolor='#999999', linewidth=0.6, alpha=0.92))
  84 
  85 # 图例
  86 from matplotlib.patches import Patch
  87 legend_labels = {
  88     'HH': f'高高聚集 ({counts.get("HH", 0)})',
  89     'LL': f'低低聚集 ({counts.get("LL", 0)})',
  90     'LH': f'低高异常 ({counts.get("LH", 0)})',
  91     'HL': f'高低异常 ({counts.get("HL", 0)})',
  92     'NS': f'不显著 ({counts.get("NS", 0)})',
  93 }
  94 legend_elements = [Patch(facecolor=cluster_colors[k], edgecolor='white',
  95                          label=legend_labels[k]) for k in ['HH', 'LL', 'LH', 'HL', 'NS']]
  96 ax.legend(handles=legend_elements, loc='lower left', fontsize=8.5,
  97           frameon=False, labelspacing=0.35, handlelength=1.6, title=f'LISA 聚类 (p < {sig_level})', title_fontsize=9)
  98 
  99 ax.set_xlim(73, 136); ax.set_ylim(17, 54)
 100 ax.set_axis_off()
 101 
 102 # Moran's I 全局统计标注
 103 ax.text(0.98, 0.98, f"Global Moran's I = {lisa.Is.mean():.4f}\n999 permutations",
 104         transform=ax.transAxes, fontsize=8.5, ha='right', va='top',
 105         bbox=dict(boxstyle='round,pad=0.4', facecolor=COLORS['bg_box'],
 106                   edgecolor=COLORS['grid'], alpha=0.95))
 107 
 108 fig.tight_layout()
 109 save_fig(fig, 'figures/fig_lisa_map.pdf')