图例未显示在Matplotlib堆叠区域图中 [英] Legend not showing up in Matplotlib stacked area plot

查看:66
本文介绍了图例未显示在Matplotlib堆叠区域图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 plt.fill_between( )的方法,尝试了很多事情之后,我仍然无法弄清为什么它不显示任何图例或标签(即使我在代码中提供了它们).这是代码:

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). 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):

帮助!

推荐答案

fill_between()命令创建一个legend()命令不支持的PolyCollection.

The fill_between() command creates a PolyCollection that is not supported by the legend() command.

因此,您将不得不使用另一个matplotlib艺术家(与legend()兼容)作为代理,而无需将其添加到坐标轴(这样就不会在主轴上绘制该代理艺术家)并将其提供给图例功能. (有关更多详细信息,请参见 matplotlib图例指南)

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. (see the matplotlib legend guide for more details)

对于您而言,下面的代码应该可以解决您的问题:

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

这篇关于图例未显示在Matplotlib堆叠区域图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆