2017-03-16 25 views
0

我創建「事件的情節」,也就是目前正在尋找這樣的添加圖例:爲fill_between不同顏色的()段

enter image description here

不過,我不知道我怎麼可以添加一個傳說只針對每個顏色組。這是劇情如何得到目前創建:

handles = dict() 

for i, channel_events in enumerate(channel_event_list): 

    for event in channel_events: 
     start = event[0] 
     end = event[1] 
     y = (i, i + padding) 

     c = 'red' if colors is None else colors[i] 

     h = plt.fill_between([start, end], y[0], y2=y[1], color=c) 

     if c not in handles: 
      handles[c] = list() 
     handles[c].append(h) 

我以爲我可以使用的fill_between()作爲提手的輸出,但似乎我錯在那裏。

那麼最簡單的方法是隻爲這裏的顏色獲取圖例?

+0

「但看來我錯了」,是不足夠的問題說明。我不明白爲什麼它不可能使用'fill_between'返回的'PolyCollection'作爲圖例句柄。 – ImportanceOfBeingErnest

回答

0

要創建fill_between調用或其他PolyCollection的圖例句柄,可以使用此PolyCollection並將其提供給圖例。

import matplotlib.pyplot as plt 

h = plt.fill_between([1,2,3],[1,3,4], y2=[1,2,3], color="#c1009b") 

plt.legend(handles=[h], labels=["MyLabel"]) 
plt.show() 

enter image description here

更簡單的方法是直接使用fill_between圖(就像任何其他的情節)的label參數創建自動圖例條目。

import matplotlib.pyplot as plt 

plt.fill_between([0,1,2],[4,3,4], y2=[3,2.5,3], color="#c1009b", label="Label1") 
plt.fill_between([0,1,1.3],[1,2,0.5], y2=[0,-1,0], color="#005ec1", label="Label2") 
plt.fill_between([2,3,4],[0.5,1,0], y2=[-1,-1,-1.5], color="#005ec1", label="_noLabel") 

plt.legend() 
plt.show() 

enter image description here

+0

完美!謝謝 :) – displayname