increase the linewidth of the legend lines in matplotlib

Andrea Zonca picture Andrea Zonca · Mar 14, 2012 · Viewed 34.1k times · Source

I know that if I change the linewidth of a line, that is automatically updated in the legend. However I would like to just change the legend linewidth without affecting the plot.

Answer

Brendan Wood picture Brendan Wood · Mar 14, 2012

Here's a simple example of how to do it:

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
p1 = plt.plot(x, y1, 'b-', linewidth=1.0)
p2 = plt.plot(x, y2, 'r-', linewidth=1.0)

# make a legend for both plots
leg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1)

# set the linewidth of each legend object
for legobj in leg.legendHandles:
    legobj.set_linewidth(2.0)

plt.show()