Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually create a legend

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.

My thought was to do:

    ax2.legend(self.labels,colorList[:len(self.labels)])     plt.legend() 

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.

Am I missing anything?

Thanks

like image 764
Brady forcier Avatar asked Sep 14 '16 21:09

Brady forcier


People also ask

How do I create a legend in ggplot2?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.


1 Answers

Have you checked the Legend Guide?

For practicality, I quote the example from the guide.

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.

Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:

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() 

enter image description here

Edit

To add two patches you can do this:

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]) 

enter image description here

like image 167
gabra Avatar answered Sep 24 '22 01:09

gabra