简体   繁体   English

传奇没有出现在Matplotlib堆积区域图中

[英]Legend not showing up in Matplotlib stacked area plot

I am creating a stacked line/area plot using plt.fill_between() method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying any legend or labels (even when I provide them in the code). 我正在使用pyplot的plt.fill_between()方法创建一个堆叠的线/面积图,在尝试了这么多东西后,我仍然无法弄清楚为什么它没有显示任何图例或标签(即使我在码)。 Here is the code: 这是代码:

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()

Here is the image generated (note that the legend shows empty box instead of labels): 这是生成的图像(请注意,图例显示空框而不是标签): 顶部的空传说框

Help! 救命!

The fill_between() command creates a PolyCollection that is not supported by the legend() command. fill_between()命令创建一个legend()命令不支持的PolyCollection。

Therefore you will have to use another matplotlib artist (compatible with legend() ) as a proxy, without adding it to the axes (so the proxy artist will not be drawn in the main axes) and feed it to the legend function. 因此,您必须使用另一个matplotlib艺术家(与legend()兼容)作为代理,而不将其添加到轴(因此代理艺术家不会在主轴中绘制)并将其提供给图例功能。 (see the matplotlib legend guide for more details) (有关详细信息,请参阅matplotlib图例指南

In your case, the code below should fix your problem: 在您的情况下,下面的代码应该解决您的问题:

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

图片

gcalmettes's answer was a helpful start, but I wanted my legend to pick up the colors that the stackplot had automatically assigned. gcalmettes的答案是一个有用的开始,但我希望我的传奇能够获取stackplot自动分配的颜色。 Here's how I did it: 我是这样做的:

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

Another, arguably easier, technique is to plot an empty data set, and use it's legend entry: 另一种可以说是更简单的技术是绘制一个空数据集,并使用它的图例条目:

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

This works well if you have other data labels for the legend, too: 如果您还有图例的其他数据标签,这也很有效:

在此输入图像描述

Only to give an update about this matter as I as looking for it. 我正在寻找它,只是提供有关此事的更新。 At 2016, PolyCollection already provide support to the label attribute as you can see: 在2016年,PolyCollection已经为label属性提供了支持,如您所见:

https://github.com/matplotlib/matplotlib/pull/3303#event-182205203 https://github.com/matplotlib/matplotlib/pull/3303#event-182205203

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM