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:
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?
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()
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])
For those wanting to add manual legend items into a single/common legend with automatically generated items:
#Imports import matplotlib.patches as mpatches # where some data has already been plotted to ax handles, labels = ax.get_legend_handles_labels() # manually define a new patch patch = mpatches.Patch(color="grey", label="Manual Label") # handles is a list, so append manual patch handles.append(patch) # plot the legend plt.legend(handles=handles, loc="upper center")
complete example with manual line and patch
import matplotlib.pyplot as plt from matplotlib.lines import Line2D import matplotlib.patches as mpatches plt.plot([1,2,3,4], [10,20,30,40], label="My Data", color="red") handles, labels = plt.gca().get_legend_handles_labels() patch = mpatches.Patch(color="grey", label="manual patch") line = Line2D(, , label="manual line", color="k") handles.extend([patch,line]) plt.legend(handles=handles) plt.show()
R for Everyone: Advanced Analytics and Graphics. ...
Become a master in Python by learning coding best practices and advanced programming concepts in Python 3.7. This book is written for Python developers who wish to go further in mastering Python. A...
The big data era is upon us: data are being generated, analyzed, and used at an unprecedented scale, and data-driven decision making is sweeping through all aspects of society. Since the value of data...
Taking into account the development of modern programming, especially the emerging programming languages that reflect modern practice, Numerical Programming: A Practical Guide for Scientists and...