Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Specifying the line width of the legend frame in Matplotlib
To specify the line width of the legend frame in Matplotlib, we can use the set_linewidth() method. This allows you to customize the appearance of legend lines independently from the actual plot lines.
Basic Example
Here's how to modify the line width of legend entries ?
import numpy as np import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create data points x = np.linspace(-5, 5, 100) y = np.sin(x) # Create plot fig, ax = plt.subplots() ax.plot(x, y, c='r', label='y=sin(x)', linewidth=3.0) # Create legend and modify line width leg = plt.legend() leg.get_lines()[0].set_linewidth(6) plt.show()
Multiple Legend Lines
When working with multiple lines, you can set different widths for each legend entry ?
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-5, 5, 100) y1 = np.sin(x) y2 = np.cos(x) fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(x, y1, 'r-', label='sin(x)', linewidth=2) ax.plot(x, y2, 'b--', label='cos(x)', linewidth=2) # Get legend and modify line widths leg = plt.legend() leg.get_lines()[0].set_linewidth(8) # sin(x) legend line leg.get_lines()[1].set_linewidth(4) # cos(x) legend line plt.grid(True, alpha=0.3) plt.show()
Alternative Method Using Legend Properties
You can also set legend line properties during legend creation ?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 50)
y1 = np.exp(-x/5) * np.cos(x)
y2 = np.exp(-x/5) * np.sin(x)
plt.figure(figsize=(8, 5))
line1, = plt.plot(x, y1, 'g-', label='Damped Cosine', linewidth=1.5)
line2, = plt.plot(x, y2, 'm-', label='Damped Sine', linewidth=1.5)
# Create legend with custom properties
leg = plt.legend()
for line, width in zip(leg.get_lines(), [5, 3]):
line.set_linewidth(width)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Legend Line Width Customization')
plt.grid(True, alpha=0.3)
plt.show()
Key Points
-
plt.legend()returns a legend object that contains line properties -
get_lines()[index]accesses individual legend lines by index -
set_linewidth()modifies only the legend line appearance, not the plot line - Legend line order matches the order of plot creation
Conclusion
Use leg.get_lines()[index].set_linewidth(width) to customize legend line widths in Matplotlib. This technique helps emphasize important data series in your legend without affecting the actual plot lines.
Advertisements
