Linestyles in Matplotlib Python
In Matplotlib we can change appearance of lines in our plots by adjusting their style and can choose between solid, dashed, dotted or dash-dot lines to make our plots easier to understand. By default it uses a solid line while plotting data but we can change the line style using linestyle
or ls
argument in plot()
method.
Syntax: plt.plot(x, y, linestyle='line_style', color='color')
where line_style
is:
Character | Definition |
---|---|
– | Solid line |
— | Dashed line |
-. | dash-dot line |
: | Dotted line |
. | Point marker |
And colors
can be:
Codes | Description |
---|---|
b | blue |
g | green |
r | red |
c | cyan |
m | magenta |
y | yellow |
k | black |
w | white |
Example 1: Dotted Line Style in Blue
x = [0, 1, 2, 3, 4]
: Define x-values for the plot.y = [0, 1, 4, 9, 16]
: Define y-values for the plot.plt.plot(x, y, linestyle=':', color='b', label='Dotted Line')
: Plot the data with a dotted blue line and label it Dotted Line.
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y, linestyle=':', color='b', label='Dotted Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Dotted Line Style')
plt.legend()
plt.show()
Output:

Example 2: Dash-dot Line Style in Yellow
plt.plot(x, y, linestyle='-.', color='y', label='Dash-dot Line')
: Plot the x and y values with a dash-dot yellow line and label it as Dash-dot Line.
import matplotlib.pyplot as plt
x = [0, 2, 4, 6, 8, 10, 12, 14]
y = [4, 2, 8, 6, 10, 5, 12, 6]
plt.plot(x, y, linestyle='-.', color='y', label='Dash-dot Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Dash-dot Line Style')
plt.legend()
plt.show()
Output:

Example 3: Dashed Line Style in Green
plt.plot(x, y, linestyle='--', color='g', label='Dashed Line')
: Plot the x and y values with a green dashed line and label it as Dashed Line.
import matplotlib.pyplot as plt
x = [0, 1, 12, 3, 4]
y = [0, 1, 14, 9, 20]
plt.plot(x, y, linestyle='--', color='g', label='Dashed Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Dashed Line Style')
plt.legend()
plt.show()
Output:

Example 4: Solid Line Style in Red
plt.plot(x, y, linestyle='-', color='r', label='Solid Line')
: Plot the x and y values with a solid red line and label it as Solid Line.
import matplotlib.pyplot as plt
x = [0, 10, 2, 13, 14]
y = [0, 11, 14, 19, 16]
plt.plot(x, y, linestyle='-', color='r', label='Solid Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Solid Line Style')
plt.legend()
plt.show()
Output:

With these simple line style customizations we can make our Matplotlib plots interactive and easier to interpret. By exploring different line styles we can focus on trends, distinguish data series and improve overall readability of our visualizations.