Trusted answers to developer questions

How to create line width in Matplotlib

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

Line width in the Matplot library is simply the size of the line of plot. When you need to give a data set of your plot a different look when compared to others, it is necessary for you to increase the line width of the plot.

The line width simply 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, you can change this size to any size of your choice.

How to change the line width of a plot

The steps to take when changing the line width of a plot are listed below:

  1. Import the various modules and libraries you need for the plot: matplot library matplot, numpy, pyplot.
  2. Create your data set(s) to be plotted.
  3. In the plot() method after declaring the linewidth parameter, you assign it to any number value you want to represent the desired width of your plot. Take a look at this code below, which uses a width size of 4:
Press + to interact
Pyplot.plot(x, y, linewidth='4')
  1. Finally, use the show() method to show your plot.

Example

Now, let’s illustrate how to change the line widths of different plots.

Press + to interact
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, you can also add markers to a line width. See this shot for more on this topic.

RELATED TAGS

matplotlib
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?