2017-03-16 88 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