Tuesday, September 24, 2024
Google search engine
HomeLanguagesLinestyles in Matplotlib Python

Linestyles in Matplotlib Python

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

The default linestyle while plotting data is solid linestyle in matplotlib. We can change this linestyle by using linestyle or ls argument of plot() method.

Following are the linestyles available in matplotlib

Using linestyle Argument:

  • Solid
  • Dashed
  • Dotted
  • Dashdot
  • None

Using ls Argument:

  • ‘-‘
  • ‘:’
  • ‘–‘
  • ‘-.’
  • ‘ ‘

Step-by-step Approach

  • Import module.
  • Create data.
  • Normally plot the data by setting linestyle or ls argument of plot() method.
  • Display plot.

Below are various programs to depict various line styles available in matplotlib module:

Example 1: Program to depict dotted line style in a plot.

Python3




# importing libraries
import matplotlib.pyplot as plt
  
# creating data
xdata = [0, 2, 4, 6, 8, 10, 12, 14]
ydata = [4, 2, 8, 6, 10, 5, 12, 6]
  
# plotting data
plt.plot(xdata, ydata, linestyle='dotted')
  
# Displaying plot
plt.show()


Output:

Example 2: Program to depict dash dot line style in a plot.

Python3




# importing libraries
import matplotlib.pyplot as plt
  
# creating data
xdata = [0, 2, 4, 6, 8, 10, 12, 14]
ydata = [4, 2, 8, 6, 10, 5, 12, 6]
  
# plotting data
plt.plot(xdata, ydata, linestyle='dashdot')
  
# Displaying plot
plt.show()


Output:

Example 3: Program to depict dashed line style in a plot using ls argument.

Python3




# importing libraries
import matplotlib.pyplot as plt
  
# creating data
xdata = [0, 2, 4, 6, 8, 10, 12, 14]
ydata = [4, 2, 8, 6, 10, 5, 12, 6]
  
# plotting data
plt.plot(xdata, ydata, ls='--')
  
# Displaying plot
plt.show()


Output:

Example 4: Program to depict solid line style in a plot using ls argument.

Python3




# importing libraries
import matplotlib.pyplot as plt
  
# creating data
xdata = [0, 2, 4, 6, 8, 10, 12, 14]
ydata = [4, 2, 8, 6, 10, 5, 12, 6]
  
# plotting data
plt.plot(xdata, ydata, ls='-')
  
# Displaying plot
plt.show()


Output:

All the above types of line styles can be visualized using the linestyle or ls argument. The none or ‘ ‘ when visualized will generate a blank plot. 

RELATED ARTICLES

Most Popular

Recent Comments