How to set linewidth of lines in Matplotlib legend

  1. set_linewidth() method
  2. matplotlib.pyplot.setp() method

We can change the linewidth of lines in Matplotlib legend by using set_linewidth() method of legend object and setp() method of the artist objects.

set_linewidth() method

The linewidth parameter in plot function can be used to control the width of the plot of a particular object and set_linewidth() method can be used to control the width of lines of the legend in Matplotlib.

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)

fig, ax = plt.subplots(figsize=(8,6))

ax.plot(x, y1, c='r', label='sinx',linewidth=3.0)
ax.plot(x, y2, c='g', label='cosx',linewidth=5.0)

leg = plt.legend()

leg.get_lines()[0].set_linewidth(6)
leg.get_lines()[1].set_linewidth(10)

plt.show() 

Output:

set linewidth of lines of a legend in Matplotlib using set_linewidth method

The line width of two lines in the plot are 3.0 and 5.0 respectively, and the line width of lines in the legend by default uses the same line width as in the plot.

leg = plt.legend()

leg.get_lines()[0].set_linewidth(6)

leg is the legend object and leg.get_lines() returns the list of line instances in the legend.

set_linewidth() could change the line width of the legend line to be other value rather than that in the plot.

matplotlib.pyplot.setp() method

matplotlib.pyplot.setp() method allows us to set the property of pyplot objects. We can use the linewidth parameter of setp() function to set linewidth of particular legend object.

 import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)

fig, ax = plt.subplots(figsize=(8,6))

ax.plot(x, y1, c='r', label='sinx',linewidth=3.0)
ax.plot(x, y2, c='g', label='cosx',linewidth=5.0)

leg = plt.legend()

leg_lines = leg.get_lines()
leg_texts = leg.get_texts()

plt.setp(leg_lines[0], linewidth=6)
plt.setp(leg_lines[1], linewidth=12)
plt.setp(leg_texts, fontsize=10)

plt.show() 

Output:

set linewidth of lines of a legend in Matplotlib using setp method

Related Article - Matplotlib Legend

  • How to Place Legend Outside of The Plot in Matplotlib
  • How to Change Legend Font Size in Matplotlib
  • How to Create A Single Legend For All Subplots in Matplotlib
  • How to remove the legend in Matplotlib
  • comments powered by Disqus