Syntax error Specifying the line width of the legend frame in Matplotlib

Specifying the line width of the legend frame in Matplotlib



To specify the line width of the legend frame in Matplotlib, we can use set_linewidth() method.

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create x and y data points using numpy.
  • Create a figure and a set of subplots using subplots() method.
  • Plot x and y using plot() method.
  • Place a legend on the figure and get the legend instance.
  • Get the lines and set the line width in the legend frame.
  • To display the figure, use show() method.

Example

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y, c='r', label='y=sinx', linewidth=3.0)

leg = plt.legend()
leg.get_lines()[0].set_linewidth(6)

plt.show()

Output

Updated on: 2021-06-05T07:39:47+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements