Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matplotlib
python
communitycreator

How to use linestyles in Matplotlib

Onyejiaku Theophilus Chidalu

Overview

A linestyle in Matplotlib is simply the style of a line plot in Matplotlib. Linestyles are used to beautify, differentiate, or give different visuals to plots in a single program.

In the Matplot library, the default linestyle whenever you make a plot without specifying the linestyle is the dash (--) linestyle.

When creating a linestyle in a plot, there are two plot() methods to choose from:

  1. Using the linestyle keywords: Here, all you need do is use certain keywords to depict the style you want for your plot. They include:
  • solid linestyle
  • dashedlinestyle
  • dashdotlinestyle
  • dotted linestyle
  • none linestyle.
  1. Using the shorter syntax ls: Here, all you need do is use the symbols representing the linestyle keywords. The shorter syntax ls and their respective linestyle keywords are shown in the table below:
Linestyle keywords ls
solid '-'
dashed '--'
dashdot '-.'
dotted ':'
none ''

Example

Let’s create a plot of a solid linestyle using linestyle keywords and ls arguments.

The following is a code snippet using the linestyle keyword argument:

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 solid linestyle
axs[0,0].plot(x, y, linestyle = 'solid')
axs[0,0].set_title('solid' )

# using the dashed linestyle
axs[0,1].plot(x, y, linestyle = 'dashed')
axs[0,1].set_title('dashed' )

# using the  dashdot linestyle
axs[1,0].plot(x, y, linestyle = 'dashdot')
axs[1,0].set_title('dash dot' )

# using the dotted linestyle
axs[1,1].plot(x, y, linestyle = 'dotted')
axs[1,1].set_title('dotted' )


plt.tight_layout()
plt.show()
Output of the code

The following is a code snippet using the ls argument:

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 solid linestyle
axs[0,0].plot(x, y, ls = '-')
axs[0,0].set_title('solid' )

# using the dashed linestyle
axs[0,1].plot(x, y, ls = '--')
axs[0,1].set_title('dashed' )

# using the  dashdot linestyle
axs[1,0].plot(x, y, ls = '-.')
axs[1,0].set_title('dash dot' )

# using the dotted linestyle
axs[1,1].plot(x, y, ls = ':')
axs[1,1].set_title('dotted' )


plt.tight_layout()
plt.show()
Output of the code

RELATED TAGS

matplotlib
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring