使用py.stackplot在同一绘图上显示两个不同的图例

2024-10-01 02:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑下面的StPoTrk,使用MyPultLIB使用PyPrPig使用^ {CD1>}创建。有两类变量,收入和支出。它们都列在同一个图例中。 double 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. 是否有办法确保图例条目的顺序与堆栈图中的顺序相匹配(在我的原始示例中,这是费用的情况,而不是收入的情况)

Tags: labels顺序情况pltkeysaxthisvalues
1条回答
网友
1楼 · 发布于 2024-10-01 02:25:39

使用当前版本的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()

Graph with dedicated legends

相关问题 更多 >