Remove the legend border in Matplotlib

Python

Matplotlib

Legend

Remove border

Luc B.

Python

Matplotlib

Legend

Legends don't need to be visually separated from a plot with a clunky border: labels can just exist within the axes with no visual distinction. This can make a plot feel seamless and slick, which suits a particular visualization style.

Code Example

This task is best accomplished with Matplotlib's object-oriented interface. The Legend.get_frame() method returns the rectangle object that bounds the legend. By setting the line width of this object to 0 using Rectangle.set_linewidth(), we remove the legend border.

import matplotlib.pyplot as plt

ax = plt.axes()

ax.plot([0, 1], [0, 1.0], label='Label 1')
ax.plot([0, 1], [0, 1.1], label='Label 2')
ax.plot([0, 1], [0, 1.2], label='Label 3')

# Remove the legend border here
l = ax.legend()
l.get_frame().set_linewidth(0)

plt.show()

png

Note that this technique can just as easily be used to make the legend border thicker by passing a different value to Rectangle.set_linewidth().

More Examples

Pyplot Interface

It is still quite possible to remove the legend border using the pyplot interface; however, it requires blending the two Matplotlib interfaces.

plt.plot([0, 1], [0, 1.0], label='Label 1')
plt.plot([0, 1], [0, 1.1], label='Label 2')
plt.plot([0, 1], [0, 1.2], label='Label 3')

# Remove the legend border here
l = plt.legend()
l.get_frame().set_linewidth(0)

plt.show()

png