How do you just show the text label in plot legend? (e.g. remove a label's line in the legend)
At that point, it's arguably easier to just use annotate
.
For example:
import numpy as npimport matplotlib.pyplot as pltdata = np.random.normal(0, 1, 1000).cumsum()fig, ax = plt.subplots()ax.plot(data)ax.annotate('Label', xy=(-12, -12), xycoords='axes points', size=14, ha='right', va='top', bbox=dict(boxstyle='round', fc='w'))plt.show()
However, if you did want to use legend
, here's how you'd do it. You'll need to explicitly hide the legend handles in addition to setting their size to 0 and removing their padding.
import numpy as npimport matplotlib.pyplot as pltdata = np.random.normal(0, 1, 1000).cumsum()fig, ax = plt.subplots()ax.plot(data, label='Label')leg = ax.legend(handlelength=0, handletextpad=0, fancybox=True)for item in leg.legendHandles: item.set_visible(False)plt.show()
You can just set the handletextpad
and handlelength
in the legend via the legend_handler
as shown below:
import matplotlib.pyplot as pltimport numpy as np# Plot up a generic set of linesx = np.arange( 3 )for i in x: plt.plot( i*x, x, label='label'+str(i), lw=5 )# Add a legend # (with a negative gap between line and text, and set "handle" (line) length to 0)legend = plt.legend(handletextpad=-2.0, handlelength=0)
Detail on handletextpad
and handlelength
is in documentation (linked here, & copied below):
handletextpad : float or None
The pad between the legend handle and text. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handletextpad"].
handlelength : float or None
The length of the legend handles. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handlelength"].
With the above code:
With a few extra lines the labels can have the same color as their line. just use .set_color()
via legend.get_texts()
.
# Now color the legend labels the same as the linescolor_l = ['blue', 'orange', 'green']for n, text in enumerate( legend.texts ): print( n, text) text.set_color( color_l[n] )
Just calling plt.legend()
gives:
I found another much simpler solution - simply set the scale of the marker to zero in the legend properties:
plt.legend(markerscale=0)
This is particularly useful in scatter plots, when you don't want the marker to be visually mistaken for a true data point (or even outlier!).