Manually add legend Items Python matplotlib
<p>I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.</p>

<p>My thought was to do:</p>

<pre><code>    ax2.legend(self.labels,colorList[:len(self.labels)])
    plt.legend()
</code></pre>

<p>Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.</p>

<p>Am I missing anything?</p>

<p>Thanks</p>

<p>Have you checked the <a href="http://matplotlib.org/users/legend_guide.html" rel="nofollow">Legend Guide</a>?</p>

<p>For practicality, I quote the example from the <a href="http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists" rel="nofollow">guide</a>.</p>

<blockquote>
  <p>Not all handles can be turned into legend entries automatically, so it
  is often necessary to create an artist which can. Legend handles donât
  have to exists on the Figure or Axes in order to be used.</p>
  
  <p>Suppose we wanted to create a legend which has an entry for some data
  which is represented by a red color:</p>
</blockquote>

<pre><code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()
</code></pre>

<p><a href="http://i.stack.imgur.com/mFZhR.png" rel="nofollow"><img src="http://i.stack.imgur.com/mFZhR.png" alt="enter image description here"></a></p>

<p><strong>Edit</strong></p>

<p>To add two patches you can do this:</p>

<pre><code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')

plt.legend(handles=[red_patch, blue_patch])
</code></pre>

<p><a href="http://i.stack.imgur.com/T1QLU.png" rel="nofollow"><img src="http://i.stack.imgur.com/T1QLU.png" alt="enter image description here"></a></p>

python matplotlib