You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib使用stackplot实现堆叠图双独立图例及顺序匹配

double stackplot

解决方案

拆分双图例实现

stackplot()调用时会返回对应堆叠层的PolyCollection对象,我们可以分别保存收入、支出两类的返回值,分两次生成图例:

  • 第一次生成收入类图例后,调用ax.add_artist()将其固定到画布上,避免第二次生成图例时被覆盖
  • 分别给两个图例指定loc参数为upper left和lower left即可实现位置分离

图例顺序与堆叠层匹配

stackplot()默认将先传入的数据集放在堆叠层最底部、后传入的放在最上方,而图例默认展示顺序和传入顺序一致,就会出现和堆叠上下顺序相反的问题。生成图例时将handles和labels同时逆序,即可保证图例条目顺序和堆叠层从上到下的顺序完全匹配。


完整可运行代码

from matplotlib import pyplot as plt
fig, ax = plt.subplots()

xVector = range(3)
earnings = {'fare': [2, 4, 6], 'tip': [1, 2, 3]}
expenses = {'maintenance': [-0.5, -1, -1.5], 'gas': [-1, -1.5, -2]}

# 分别保存两次stackplot返回的PolyCollection对象
earnings_collections = ax.stackplot(xVector, earnings.values(), labels=earnings.keys())
expenses_collections = ax.stackplot(xVector, expenses.values(), labels=expenses.keys())

# 生成收入类图例(逆序匹配堆叠顺序),固定到画布
earnings_legend = ax.legend(handles=reversed(earnings_collections), 
                           labels=reversed(list(earnings.keys())),
                           loc='upper left', 
                           title='收入')
ax.add_artist(earnings_legend)

# 生成支出类图例,若你当前环境支出顺序已经匹配,可去掉两个reversed()
ax.legend(handles=reversed(expenses_collections),
          labels=reversed(list(expenses.keys())),
          loc='lower left',
          title='支出')

plt.xlabel('time')
plt.ylabel('currency')

plt.show()

内容的提问来源于stack exchange,提问作者Unis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 17:54:00