Matplotlib堆叠面积图中未显示图例

28 投票
4 回答
22840 浏览
提问于 2025-04-17 13:43

我正在使用 plt.fill_between() 方法来创建一个堆叠的折线图/区域图,但尝试了很多方法后,我还是搞不明白为什么图例和标签不显示(即使我在代码中提供了它们)。以下是我的代码:

import matplotlib.pyplot as plt
import numpy

a1_label = 'record a1'
a2_label = 'record a2'

a1 = numpy.linspace(0,100,40)
a2 = numpy.linspace(30,100,40)

x = numpy.arange(0, len(a1), 1)

plt.fill_between(x, 0, a1, facecolor='green')
plt.fill_between(x, a1, a2, facecolor='red')
plt.title('some title')
plt.grid('on')
plt.legend([a1_label, a2_label])
plt.show()

这是生成的图像(注意图例显示的是空框而不是标签):

empty legend box at the top

求助!

4 个回答

18

另一种可以说更简单的方法是先绘制一个空的数据集,然后利用它的图例条目:

plt.plot([], [], color='green', linewidth=10)
plt.plot([], [], color='red', linewidth=10)

如果你还有其他数据标签可以用来做图例,这个方法效果会更好:

在这里输入图片描述

19

gcalmettes的回答给了我一个很好的开始,但我希望我的图例能自动获取堆叠图中分配的颜色。下面是我实现的方法:

polys = pyplot.stackplot(x, y)
legendProxies = []
for poly in polys:
    legendProxies.append(pyplot.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0]))
41

fill_between()这个命令会创建一个叫做PolyCollection的东西,但这个东西不被legend()命令支持。

所以你需要用另一个和legend()兼容的matplotlib艺术家作为替代,记得不要把它加到坐标轴上(这样替代的艺术家就不会在主坐标轴上显示),然后把它传给legend函数。(想了解更多,可以查看matplotlib的图例指南

在你的情况下,下面的代码应该能解决你的问题:

from matplotlib.patches import Rectangle

p1 = Rectangle((0, 0), 1, 1, fc="green")
p2 = Rectangle((0, 0), 1, 1, fc="red")
legend([p1, p2], [a1_label, a2_label])

image

撰写回答