1 import numpy as np
   2 import matplotlib.pyplot as plt
   3 import matplotlib.colors as mcolors
   4 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   5 setup_style()
   6 
   7 categories = ['2019', '2020', '2021', '2022', '2023']
   8 components = {
   9     '第一产业': [8.2, 7.8, 7.5, 7.2, 6.9],
  10     '第二产业': [38.5, 37.2, 36.8, 36.1, 35.5],
  11     '第三产业': [53.3, 55.0, 55.7, 56.7, 57.6],
  12 }
  13 
  14 fig, ax = plt.subplots(figsize=(8, 5.5))
  15 x = np.arange(len(categories))
  16 bottom = np.zeros(len(categories))
  17 bar_width = 0.55
  18 
  19 for i, (name, vals) in enumerate(components.items()):
  20     vals_arr = np.array(vals)
  21     # ★ 淡色填充 + 原色边框
  22     bars = ax.bar(x, vals_arr, bar_width, bottom=bottom,
  23                   color=_lighten(PALETTE[i], 0.4), edgecolor=PALETTE[i],
  24                   linewidth=1.2, label=name, zorder=2)
  25 
  26     # 自动对比度标签:深色块白字 / 浅色块黑字
  27     for bar, v, b in zip(bars, vals_arr, bottom):
  28         if v > 5:
  29             r, g, b_c = mcolors.to_rgb(_lighten(PALETTE[i], 0.4))
  30             luminance = 0.299 * r + 0.587 * g + 0.114 * b_c
  31             text_color = 'white' if luminance < 0.6 else COLORS['text']
  32             ax.text(bar.get_x() + bar.get_width() / 2, b + v / 2,
  33                     f'{v:.1f}%', ha='center', va='center', fontsize=8,
  34                     color=text_color, fontweight='bold')
  35     bottom += vals_arr
  36 
  37 # 顶部趋势折线(总量)
  38 totals = bottom
  39 ax.plot(x, totals, 'o-', color=COLORS['text'], linewidth=1.5, markersize=5,
  40         markeredgecolor='white', markeredgewidth=1, zorder=3)
  41 for xi, t in zip(x, totals):
  42     ax.text(xi, t + 1.0, f'{t:.1f}', ha='center', va='bottom', fontsize=8,
  43             fontweight='bold', color=COLORS['text'])
  44 
  45 # 末端同比变化标注
  46 for i, (name, vals) in enumerate(components.items()):
  47     change = vals[-1] - vals[-2]
  48     sign = '+' if change >= 0 else ''
  49     color = COLORS['up'] if change >= 0 else COLORS['down']
  50     y_pos = sum(components[n][-1] for n in list(components.keys())[:i]) + vals[-1] / 2
  51     ax.annotate(f'{sign}{change:.1f}%', xy=(len(categories) - 1 + 0.35, y_pos),
  52                 fontsize=7, color=color, fontweight='bold', va='center',
  53                 bbox=dict(boxstyle='round,pad=0.15', facecolor='white',
  54                           edgecolor=color, alpha=0.8, linewidth=0.5))
  55 
  56 ax.set_xticks(x)
  57 ax.set_xticklabels(categories, fontsize=10)
  58 ax.set_ylabel('占比 (%)', fontsize=11)
  59 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=9, loc='upper left')
  60 ax.grid(axis='y', alpha=0.12, linestyle='--', color=COLORS['grid'])
  61 ax.spines['top'].set_visible(False)
  62 ax.spines['right'].set_visible(False)
  63 fig.tight_layout()
  64 save_fig(fig, 'figures/fig_stacked_bar.pdf')