簡體   English   中英

傳奇沒有出現在Matplotlib堆積區域圖中

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

我正在使用pyplot的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()

這是生成的圖像(請注意,圖例顯示空框而不是標簽): 頂部的空傳說框

救命!

fill_between()命令創建一個legend()命令不支持的PolyCollection。

因此,您必須使用另一個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])

圖片

gcalmettes的答案是一個有用的開始,但我希望我的傳奇能夠獲取stackplot自動分配的顏色。 我是這樣做的:

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

另一種可以說是更簡單的技術是繪制一個空數據集,並使用它的圖例條目:

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

如果您還有圖例的其他數據標簽,這也很有效:

在此輸入圖像描述

我正在尋找它,只是提供有關此事的更新。 在2016年,PolyCollection已經為label屬性提供了支持,如您所見:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM