Specifying the line width of the legend frame in Matplotlib

MatplotlibPythonData Visualization

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

raja
Published on 05-Jun-2021 07:39:20
Advertisements