2

I want to show a legend text but without a key (the rectangular box or line that appears by default).

plt.hist(x, label = 'something')

enter image description here

I don't want the box next to the legend "something". How to remove it?

Peaceful
  • 4,920
  • 15
  • 54
  • 79

2 Answers2

11

First of all, you may decide not to create a legend at all and instead put some label in to corner of the plot.

import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(size=160)
plt.hist(x)

plt.text(0.95,0.95, 'something', ha="right", va="top", transform=plt.gca().transAxes)
plt.show()

enter image description here

If you already created the legend and want to remove it, you can do so by

plt.gca().get_legend().remove()

and then add the text instead.

If this is not an option, you may set the legend handle invisible like so:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(size=160)
plt.hist(x, label = 'something')

plt.legend()

leg = plt.gca().get_legend()
leg.legendHandles[0].set_visible(False)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

Following the matplotlib docs, you can change the handlelength and handletextpad parameters to remove the handle and the space behind the label text

import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(size=160)
plt.hist(x, label = 'something')
plt.legend(handlelength=0, handletextpad=0, loc='upper right')

plt.show()

enter image description here

Medulla Oblongata
  • 3,771
  • 8
  • 36
  • 75