How to hide / remove legend line and keep shortcut
As I showed in the picture:
I don't want to show the line in the legend, but the shortcut, if possible please help fix.
Tried minimizing the line and label of the current legend and only overwrite the new label, but the legend returns both.
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')
source to share
At this point, it might be easier to just use annotate
.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = 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 want to use legend
, here's how you would do it. You will need to explicitly hide the legend descriptors in addition to setting their size to 0 and removing their padding.
import numpy as np
import matplotlib.pyplot as plt
data = 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()
source to share
You can simply install handletextpad
and handlelength
in the legend via 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)
More on handletextpad
and handlelength
in the documentation ( linked here and copied below):
handletextpad : float or None
Shim between legend handle and text. Measured in unit font sizes. Default value: None, which will be set to rcParams ["legend.handletextpad"].
descriptor length : float or None
The length of the descriptors. Measured in units of font size. The default is None, which will take a value from rcParams ["legend.handlelength"].
With the above code:
With multiple additional lines, 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] )
Just the call plt.legend()
gives:
source to share