Sometimes you don't want a legend that is explicitly tied to data that
you have plotted. For example, say you have plotted 10 lines, but don't
want a legend item to show up for each one. If you simply plot the lines
and call ax.legend(), you will get the following:
importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlibasmplfrommatplotlibimportcycler# Fixing random state for reproducibilitynp.random.seed(19680801)
Since the data does not have any labels, creating a legend requires
us to define the icons and labels.
In this case, we can compose a legend using Matplotlib objects that aren't
explicitly tied to the data that was plotted. For example:
There are many other Matplotlib objects that can be used in this way. In the
code below we've listed a few common ones.
frommatplotlib.linesimportLine2Dfrommatplotlib.patchesimportPatchlegend_elements=[Line2D([0],[0],color='b',lw=4,label='Line'),Line2D([0],[0],marker='o',color='w',label='Scatter',markerfacecolor='g',markersize=15),Patch(facecolor='orange',edgecolor='r',label='Color Patch')]# Create the figurefig,ax=plt.subplots()ax.legend(handles=legend_elements,loc='center')plt.show()
Total running time of the script: (0 minutes 1.598 seconds)