Removing duplicate mpatches from a list
<p>I startet to work with buttons in my plots (<code>from matplotlib.widgets import Button</code>). By pressing the buttons different plots will show up. For that reason my legends do change. I handle this by putting the mpatches in a list:</p>

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

<p>Now if I press the same button twice, the red_patch will also be displayed twice. Because of that I want to delete duplicates but this won't work. So far I tried:</p>

<pre><code>list(set(handelist))
</code></pre>

<p>and also:</p>

<pre><code>if red_patch not in handelist:
    handlelist.append(red_patch)
</code></pre>

<p>But both won't work and I don't understand why. Hope you have an idea :) </p>

<p>The problem is that:</p>

<pre><code>red_patch = mpatches.Patch(color='red', label='Numerical average')
</code></pre>

<p>creates an instance of <code>red_patch</code> every time. The <code>__eq__</code> operator seems to be unimplemented for this particular type, so the <code>set</code> only compares references of the object, which are not equal.</p>

<p>I would suggest the following code instead:</p>

<pre><code># 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)
</code></pre>

<p>The key of your dictionary is the couple <code>(color,label)</code> and when you call the <code>legend</code> method you only get one <code>red_patch</code>, because if the entry already exists, no extra <code>Patch</code> will be created.</p>

<p>Of course, you have to do the same in other parts of your code where you update <code>handlelist</code>. A shared method would be handy:</p>

<pre><code>def create_patch(color,label):
   if (color,label) not in handlelist:
       handlelist[(color,label)] = mpatches.Patch(color=color, label=label)
</code></pre>

<p>EDIT: if you have only 1 patch total, you could do even simpler:</p>

<pre><code>p = mpatches.Patch(color='red', label='Numerical average')
ax.legend([p], numpoints=1)
</code></pre>

python matplotlib