2016-10-16 17 views
0

私は私のプロット(from matplotlib.widgets import Button)のボタンを使って作業を開始します。ボタンを押すと、異なるプロットが表示されます。その理由から、私の伝説は変わる。私は、リストにmpatchesを置くことによって、これを処理:リストから重複したマッチを削除する

red_patch = mpatches.Patch(color='red', label='Numerical average') 
handlelist.append(red_patch) 
ax.legend(handles=handlelist, numpoints=1) 

を今、私は二度同じボタンを押すと、red_pa​​tchも2回表示されます。そのため、私は重複を削除したいが、これは動作しません。また

list(set(handelist)) 

と::これまでのところ私が試した

if red_patch not in handelist: 
    handlelist.append(red_patch) 

をしかし、両方が動作しませんし、私はその理由を理解していません。

red_patch = mpatches.Patch(color='red', label='Numerical average') 

red_patch毎回のインスタンスを作成します。あなたのアイデア:)

答えて

1

問題はそれであると思っています。 __eq__演算子は、この特定の型に対して実装されていないようです。したがって、setは、オブジェクトの参照を比較します。

私の代わりに以下のコードをお勧めします:

# declare as ordered dict (so order of creation matters), not list 
import collections 
handlelist = collections.OrderedDict() 

color = 'red' 
label = 'Numerical average' 

if (color,label) not in handlelist: 
    handlelist[(color,label)] = mpatches.Patch(color=color, label=label) 

# pass the values of the dict as list (legend expects a list) 
ax.legend(handles=list(handlelist.values()), numpoints=1) 

エントリはすでに、余分に存在しない場合ので、あなたの辞書のキーはカップル(color,label)であり、あなたがlegendメソッドを呼び出すときに一つだけred_patchを取得Patchが作成されます。

もちろん、コードの他の部分でも、handlelistを更新する必要があります。共有方法が便利でしょう:

def create_patch(color,label): 
    if (color,label) not in handlelist: 
     handlelist[(color,label)] = mpatches.Patch(color=color, label=label) 

EDIT:あなたが唯一の1パッチの合計を持っている場合は、あなたがさらに簡単行うことができます:あなたの助けを

p = mpatches.Patch(color='red', label='Numerical average') 
ax.legend([p], numpoints=1) 
+0

ありがとう!私はあなたのコードを試しましたが、現時点でエラーが発生しました: 'RCD8.py"、行141、 ax.legend(handles = handlelist.values()、numpoints = 1) ファイル "anaconda/lib/python3 (ラベル[:]、ハンドル[:]): TypeError: 'dict_values'オブジェクトは添字付きではありません。 ' – HighwayJohn

+0

私は' list'に変換しました。今ではsubscriptableでなければなりません。また、OrderedDictとして辞書を変更したのです。 –

+0

ありがとうございます!私は以前のコード 'del handlelist [:]'で仕事をしていましたが、ここでは何を変更しなければなりませんか? – HighwayJohn

関連する問題