【发布时间】:2021-05-14 05:29:20
【问题描述】:
考虑以下堆栈图,它是使用来自 matplotlib 的 pyplot 使用 stackplot() 创建的。有两种类型的变量,收入和费用。它们都列在同一个图例中。
我想要两个独立的图例,一个用于收入,一个用于支出。已经有one example of how this can be done on this site,但它不适用于stackplot() 创建的PolyCollection。
这是一个只有一个图例的 MWE:
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]}
ax.stackplot(xVector, earnings.values(), labels=earnings.keys())
ax.stackplot(xVector, expenses.values(), labels=expenses.keys())
plt.legend(loc='upper left')
plt.xlabel('time')
plt.ylabel('currency')
plt.show()
- 如何将上述图例一分为二,左上角显示收入,左下角显示费用?
- 有没有办法确保图例条目的顺序与堆栈图中的顺序相匹配(在我的原始示例中,这是费用的情况,而不是收入的情况)?
【问题讨论】:
-
你使用的是什么版本的 matplotlib?链接的问题使用 PolyCollection 对我有用
标签: python matplotlib legend