【问题标题】:Two different legends on same plot with py.stackplotpy.stackplot 在同一情节上的两个不同图例
【发布时间】: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()
  1. 如何将上述图例一分为二,左上角显示收入,左下角显示费用?
  2. 有没有办法确保图例条目的顺序与堆栈图中的顺序相匹配(在我的原始示例中,这是费用的情况,而不是收入的情况)?

【问题讨论】:

  • 你使用的是什么版本的 matplotlib?链接的问题使用 PolyCollection 对我有用

标签: python matplotlib legend


【解决方案1】:

使用当前版本的 Matplotlib,可以按照this answer from a different thread 实现多个图例,如下所示(颠倒图例条目的顺序也很简单)。

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]}

earningsPlot = ax.stackplot(xVector, earnings.values())
expensesPlot = ax.stackplot(xVector, expenses.values())

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

earningPlotLegend = plt.legend(earningsPlot[::-1], list(earnings.keys())[::-1], loc='upper left')
plt.legend(expensesPlot, expenses.keys(), loc='lower left')
plt.gca().add_artist(earningPlotLegend)

plt.show()

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2012-09-27
    • 2015-12-21
    • 2021-07-29
    相关资源
    最近更新 更多