How to create line width in Matplotlib

Overview

Line width in the Matplot library is the size of the line of the plot. When we want to give a different look to a data set of our plot compared to others, we must increase the line width of the plot.

The line width helps to give a unique description or visual to a particular data set in a plot.

The default value for the line width of a plot in Matplotlib is 1. However, we can change this size to any size of our choice.

How to change the line width of a plot

We can follow the below step to change the line width of a plot:

  1. Import the modules and libraries we need for the plot: matplot library matplot, numpy, and pyplot.
  2. Create the data set(s) to be plotted.
  3. In the plot() method, after declaring the linewidth parameter, we assign it to any number value we want to represent the desired width of our plot. The code below uses a width size of 4:
Pyplot.plot(x, y, linewidth='4')
  1. Use the show() method to show the plot.

Example

Let’s illustrate how to change the line widths of different plots:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
fig,axs = plt.subplots(2,2)
# using the devault linewidth value 1
axs[0,0].scatter(x, y)
axs[0,0].set_title('Linewidth of 1' )
# using the devault linewidth value 1
axs[0,1].scatter(x, y, linewidth=2)
axs[0,1].set_title('Linewidth of 2' )
# using the devault linewidth value 1
axs[1,0].scatter(x, y, linewidth=4)
axs[1,0].set_title('Linewidth of 4' )
# using the devault linewidth value 1
axs[1,1].scatter(x, y, linewidth=6)
axs[1,1].set_title('Linewidth of 6' )
plt.tight_layout()
plt.show()

Interestingly, we can also add markers to the line width. See this Answer for more on this topic.

Free Resources