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
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.
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()
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With