Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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') 
like image 637
Java.beginner Avatar asked Aug 04 '14 16:08

Java.beginner


People also ask

How do I skip legend entries?

1- Select the curve you don't want have legend. 2- Go to the "more properties" (while the curve is still selected). 3- Turn "HandleVisibility" off.


1 Answers

At that point, it's arguably 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() 

enter image description here

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 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() 

enter image description here

like image 57
Joe Kington Avatar answered Oct 01 '22 02:10

Joe Kington