核心特性:浮动柱子(Floating Bars) + 连接线 + 锚点着色 + 自动数据标注
# IB配色系统
IB_COLORS = {
'primary': '#1a365d', # 深蓝 - 主数据
'accent': '#d97706', # 金橙 - 强调/总计
'positive': '#059669', # 柔绿 - 正向变动
'negative': '#dc2626', # 柔红 - 负向变动
}
def ib_waterfall_chart(categories, values, title,
unit='$', decimals=0):
fig, ax = plt.subplots(figsize=(12, 7), dpi=150)
n = len(values)
bottoms = [0]
colors = []
running_total = values[0]
for i in range(1, n - 1):
bottoms.append(running_total)
colors.append(IB_COLORS['positive']
if values[i] >= 0
else IB_COLORS['negative'])
running_total += values[i]
bottoms.append(0)
colors.append(IB_COLORS['primary'])
bar_width = 0.6
bars = ax.bar(range(n), [abs(v) for v in values],
bottom=bottoms, width=bar_width,
color=colors, edgecolor='white',
linewidth=0.8)
# 起止锚点特殊着色
bars[0].set_color(IB_COLORS['primary'])
bars[-1].set_color(IB_COLORS['accent'])
bars[-1].set_linewidth(2)
# 连接线(浮动效果)
for i in range(n - 1):
y_start = bottoms[i] + abs(values[i])
y_end = bottoms[i+1] if i < n-2 else bottoms[i+1]
ax.plot([i+bar_width/2, i+1-bar_width/2],
[y_start, y_end], color='#e5e7eb',
linewidth=1, linestyle='--')
# 数据标签...
# (完整代码见正文Markdown文件)
↓ 完整可运行代码含连接线、标注、图例、DPI设置,约130行 ↓