1 import numpy as np, matplotlib.pyplot as plt
   2 import matplotlib.patches as mpatches
   3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   4 setup_style()
   5 
   6 categories = ['初始值', '原材料', '人工', '运输', '税费', '折旧', '管理费', '利润', '最终值']
   7 values = [100, -15, -20, -8, -12, -5, -3, 0, 0]
   8 # 计算累积值
   9 cumulative = [100]
  10 for v in values[1:-1]:
  11     cumulative.append(cumulative[-1] + v)
  12 cumulative.append(cumulative[-1])
  13 values[-1] = cumulative[-1]
  14 
  15 fig, ax = plt.subplots(figsize=(10, 5))
  16 ax.grid(axis='y', alpha=0.12, linestyle='--'); ax.set_axisbelow(True)
  17 
  18 bottoms = []
  19 for i in range(len(categories)):
  20     if i == 0 or i == len(categories)-1:
  21         bottoms.append(0)
  22     else:
  23         bottoms.append(min(cumulative[i-1], cumulative[i]))
  24 
  25 for i in range(len(categories)):
  26     if i == 0 or i == len(categories)-1:
  27         c = PALETTE[0]
  28         h = cumulative[i]
  29     elif values[i] >= 0:
  30         c = COLORS['up']
  31         h = values[i]
  32     else:
  33         c = COLORS['down']
  34         h = abs(values[i])
  35 
  36     ax.bar(i, h, bottom=bottoms[i], width=0.6,
  37            color=_lighten(c, 0.3), edgecolor=c, linewidth=1.3, zorder=3)
  38 
  39     # 数值标注
  40     val_y = bottoms[i] + h + 1
  41     sign = '+' if values[i] > 0 and i > 0 else ''
  42     ax.text(i, val_y, f'{sign}{values[i] if i < len(categories)-1 else cumulative[i]}',
  43             ha='center', va='bottom', fontsize=8.5, fontweight='bold', color=c)
  44 
  45     # 连接线
  46     if i < len(categories) - 1:
  47         ax.plot([i+0.3, i+0.7], [cumulative[i], cumulative[i]],
  48                 color=COLORS['ref_line'], linewidth=0.8, linestyle='--', alpha=0.5)
  49 
  50 ax.set_xticks(range(len(categories)))
  51 ax.set_xticklabels(categories, fontsize=10, rotation=15, ha='right')
  52 ax.set_ylabel('金额(万元)', fontsize=11)
  53 ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  54 fig.tight_layout()
  55 save_fig(fig, 'figures/fig_waterfall.pdf')