2016-10-14 19 views
4
私は、曲線の間のいくつかの領域が定義されているこのプロットを持っています。伝説にそれらを含める方法はありますか?特に、それらの塗りつぶされた領域が重なり合っているだけでなく、新たな異なる色が現れているところ。

または、曲線のデータに関係なく任意の凡例を定義する可能性はありますか? enter image description herePythonのユーザー定義の凡例

+1

(http://stackoverflow.com/questions/13303928/how-to-make-custom-legend-in-matplotlib)[このスレッドで]を見てください。その答えは、カスタムレジェンドエントリの作成について説明しています。 – Ian

+2

正確にこのユースケースの例であるhttp://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artistsを参照してください。 – tacaswell

答えて

2

fill_bettweenを使用してデータをプロットすると、凡例に塗りつぶした領域が自動的に含まれます。

2つのデータセットが重なる領域を含めるには、両方のデータセットの凡例ハンドルを1つの凡例ハンドルに結合します。

コメントで指摘したように、任意の凡例ハンドルをプロキシで定義することもできます。

最後に、グラフにプロットされたデータに関係なく、凡例に表示するハンドルとラベルを正確に定義することができます。

それ以下MWEは、上記で述べたポイントを示してください:

import matplotlib.pyplot as plt 
import numpy as np 

plt.close('all') 

# Gererate some datas: 
x = np.random.rand(50) 
y = np.arange(len(x)) 

# Plot data: 
fig, ax = plt.subplots(figsize=(11, 4)) 
fillA = ax.fill_between(y, x-0.25, 0.5, color='darkolivegreen', alpha=0.65, lw=0) 
fillB = ax.fill_between(y, x, 0.5, color='indianred', alpha=0.75, lw=0) 

linec, = ax.plot(y, np.zeros(len(y))+0.5, color='blue', lw=1.5) 
linea, = ax.plot(y, x, color='orange', lw=1.5) 
lineb, = ax.plot(y, x-0.25, color='black', lw=1.5) 

# Define an arbitrary legend handle with a proxy: 
rec1 = plt.Rectangle((0, 0), 1, 1, fc='blue', lw=0, alpha=0.25) 

# Generate the legend: 
handles = [linea, lineb, linec, fillA, fillB, (fillA, fillB), 
      rec1, (fillA, fillB, rec1)] 
labels = ['a', 'b', 'c', 'A', 'B', 'A+B', 'C', 'A+B+C'] 
ax.legend(handles, labels, loc=2, ncol=4) 

ax.axis(ymin=-1, ymax=2) 

plt.show() 

enter image description here

1

はい、あなたは絶対的に正しいian_itor、tacaswellとジャンセバスチャンあり、ユーザ定義の伝説は、ユニークなソリューションであるように思わさらに、曲線と区別できるように別の線幅を作って、アルファベットで遊んでいれば、正しい色が得られました。

handles, labels = ax.get_legend_handles_labels() 
display = (0,1,2,3,4) 

overlap_1 = plt.Line2D((0,1),(0,0), color='firebrick', linestyle='-',linewidth=15, alpha = 0.85) 
overlap_2= plt.Line2D((0,1),(0,0), color='darkolivegreen',linestyle='-',linewidth=15, alpha = 0.65) 
over_lo_3= plt.Line2D((0,1),(0,0), color='indianred',linestyle='-',linewidth=15, alpha = 0.75) 

ax.legend([handle for i,handle in enumerate(handles) if i in display]+[overlap_1 , overlap_2 , overlap_3 ], 
     [label for i,label in enumerate(labels) if i in display]+['D','F','G']) 

enter image description here

+0

代わりに'over_lo_3'に適切な色を見つけるために演奏すると、凡例を定義するときに' over_lo_3'の代わりに '(overlap_1、overlap_2)'を使うだけで 'overlap_1'と' overlap_2'ハンドルを単純に組み合わせることもできました。しかし、あなたの解決策もうまくいくので、良い仕事です。 –

+0

ありがとう! – Hamidreza