1 import numpy as np
   2 import matplotlib.pyplot as plt
   3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   4 setup_style()
   5 
   6 items = ['缺陷A', '缺陷B', '缺陷C', '缺陷D', '缺陷E', '缺陷F', '缺陷G', '缺陷H']
   7 values = np.array([45, 32, 18, 12, 8, 5, 3, 2])
   8 # 按值排序
   9 sort_idx = np.argsort(-values)
  10 items = [items[i] for i in sort_idx]
  11 values = values[sort_idx]
  12 
  13 cumulative_pct = np.cumsum(values) / values.sum() * 100
  14 
  15 fig, ax1 = plt.subplots(figsize=(9, 5.5))
  16 ax2 = ax1.twinx()
  17 
  18 x = np.arange(len(items))
  19 
  20 # ★ 淡色填充 + 原色边框柱
  21 bars = ax1.bar(x, values, width=0.6,
  22                color=_lighten(PALETTE[0], 0.4), edgecolor=PALETTE[0],
  23                linewidth=1.2, zorder=2)
  24 
  25 # 80% 分界线之前的柱子高亮
  26 threshold_idx = np.searchsorted(cumulative_pct, 80)
  27 for i in range(threshold_idx + 1):
  28     bars[i].set_facecolor(_lighten(PALETTE[0], 0.25))
  29     bars[i].set_linewidth(1.8)
  30 
  31 # 顶部数值标注
  32 for bar, v in zip(bars, values):
  33     ax1.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.5,
  34              f'{v}', ha='center', va='bottom', fontsize=8, fontweight='bold',
  35              color=COLORS['text'])
  36 
  37 # 累积百分比折线
  38 ax2.plot(x, cumulative_pct, 'o-', color=PALETTE[1], linewidth=2, markersize=6,
  39          markeredgecolor='white', markeredgewidth=1.2, zorder=3)
  40 
  41 # 80% 分界线
  42 ax2.axhline(y=80, color=COLORS['down'], linestyle='--', linewidth=1, alpha=0.6)
  43 ax2.text(len(items) - 0.5, 81, '80%', fontsize=9, color=COLORS['down'],
  44          fontweight='bold', ha='right',
  45          bbox=dict(boxstyle='round,pad=0.2', facecolor='white',
  46                    edgecolor=COLORS['down'], alpha=0.8))
  47 
  48 # 80% 区域阴影
  49 ax1.axvspan(-0.5, threshold_idx + 0.5, alpha=0.05, color=PALETTE[0], zorder=0)
  50 ax1.text(threshold_idx / 2, max(values) * 0.9, '关键少数 (80%)',
  51          ha='center', fontsize=9, color=PALETTE[0], style='italic',
  52          bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
  53                    edgecolor=PALETTE[0], alpha=0.8))
  54 
  55 ax1.set_xticks(x)
  56 ax1.set_xticklabels(items, fontsize=9, rotation=15, ha='right')
  57 ax1.set_ylabel('频次', fontsize=11, color=PALETTE[0])
  58 ax2.set_ylabel('累积百分比 (%)', fontsize=11, color=PALETTE[1])
  59 ax1.tick_params(axis='y', labelcolor=PALETTE[0])
  60 ax2.tick_params(axis='y', labelcolor=PALETTE[1])
  61 ax2.set_ylim(0, 105)
  62 ax1.spines['top'].set_visible(False)
  63 ax1.grid(axis='y', alpha=0.12, linestyle='--', color=COLORS['grid'])
  64 fig.tight_layout()
  65 save_fig(fig, 'figures/fig_pareto.pdf')