How do you just show the text label in plot legend? (e.g. remove a label's line in the legend)

Java.beginner picture Java.beginner · Aug 4, 2014 · Viewed 21.8k times · Source

I want to show the text for a line's label in the legend, but not a line too (As shown in the figure below):

enter image description here

I have tried to minimise the legend's line and label, and overwrite only the new-label too (as in the code below). However, the legend brings both back.

    legend = ax.legend(loc=0, shadow=False) 
    for label in legend.get_lines(): 
        label.set_linewidth(0.0) 
    for label in legend.get_texts(): 
        label.set_fontsize(0) 

    ax.legend(loc=0, title='New Title')

Answer

tsherwen picture tsherwen · Apr 6, 2018

You can just set the handletextpad and handlelength in the legend via the legend_handler as shown below:

import matplotlib.pyplot as plt
import numpy as np
# Plot up a generic set of lines
x = 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:

enter image description here

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 lines
color_l = ['blue', 'orange', 'green']
for n, text in enumerate( legend.texts ):
    print( n, text)
    text.set_color( color_l[n] )

enter image description here

Just calling plt.legend() gives:

enter image description here