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 labels = ['类别A', '类别B', '类别C', '类别D', '类别E'] 7 sizes = [35, 25, 20, 12, 8] 8 prev_sizes = [32, 27, 19, 14, 8] # 上期数据(用于计算变化率) 9 explode = [0.03] * len(labels) 10 11 fig, ax = plt.subplots(figsize=(7, 6)) 12 13 # ★ 淡色填充 + 原色边框 14 wedge_colors = [_lighten(PALETTE[i], 0.4) for i in range(len(labels))] 15 edge_colors = [PALETTE[i] for i in range(len(labels))] 16 17 wedges, texts = ax.pie( 18 sizes, labels=None, startangle=90, 19 colors=wedge_colors, explode=explode, 20 wedgeprops=dict(width=0.45, edgecolor='white', linewidth=0), 21 pctdistance=0.75) 22 23 # 原色边框(单独绘制,避免白色分隔线被覆盖) 24 for wedge, ec in zip(wedges, edge_colors): 25 wedge.set_edgecolor(ec) 26 wedge.set_linewidth(1.5) 27 28 # 外部连线标签 + 变化率 29 for i, (wedge, label, size, prev) in enumerate(zip(wedges, labels, sizes, prev_sizes)): 30 ang = (wedge.theta2 + wedge.theta1) / 2 31 x_label = np.cos(np.radians(ang)) * 1.35 32 y_label = np.sin(np.radians(ang)) * 1.35 33 x_conn = np.cos(np.radians(ang)) * 1.05 34 y_conn = np.sin(np.radians(ang)) * 1.05 35 36 # 连线 37 ax.plot([x_conn, x_label], [y_conn, y_label], '-', color=PALETTE[i], 38 linewidth=0.8, alpha=0.6) 39 40 # 标签 + 百分比 + 变化率 41 change = size - prev 42 sign = '+' if change >= 0 else '' 43 change_color = COLORS['up'] if change >= 0 else COLORS['down'] 44 ha = 'left' if x_label > 0 else 'right' 45 ax.text(x_label, y_label, 46 f'{label}\n{size}% ({sign}{change}%)', 47 ha=ha, va='center', fontsize=9, color=PALETTE[i], 48 fontweight='bold', 49 bbox=dict(boxstyle='round,pad=0.2', facecolor='white', 50 edgecolor=PALETTE[i], alpha=0.8, linewidth=0.5)) 51 52 # 中心文字 53 ax.text(0, 0, '总计\n100%', ha='center', va='center', fontsize=14, 54 fontweight='bold', color=COLORS['text']) 55 56 ax.set_aspect('equal') 57 fig.tight_layout() 58 save_fig(fig, 'figures/fig_donut.pdf')