Change the line pattern in Matplotlib

Python

Matplotlib

Line

Change pattern

Luc B.

Python

Matplotlib

Line Plot

Sometimes plots benefit from having something other than solid lines representing trends. For example, a line can be drawn with dashes to deemphasize it and imply it's there just for comparison or reference. This, in cooperation with changing the marker style or line width, can make visualizations much easier to interpret.

Code Example

Use the format string parameter to plt.plot() to change the marker style in Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

x_values = np.arange(0, 7)
y_values = np.array([0.27, 0.32, 0.35, 0.49, 0.55, 0.7, 0.95])

# Adjust the line pattern here
plt.plot(x_values, y_values, "--")       # Make line dashed
plt.plot(x_values, y_values + 0.5, "-.") # Make line dot-dashed
plt.plot(x_values, y_values + 1, ":")    # Make line dotted

plt.legend(['Dashed', 'Dot-Dashed', 'Dotted'])
plt.show()

png

The supported line style abbreviations are:

'-'    # solid line
'--'   # dashed line
'-.'   # dot-dashed line
':'    # dotted line

More Examples

Use the linestyle Parameter

If you're adverse to using plt.plot()'s format string, you can use the linestyle parameter instead.

import matplotlib.pyplot as plt

# Use the linestyle parameter
plt.plot(x_values, y_values, linestyle=':')

plt.show()

png