In the previous part of the Matplotlib series we were adding Axes to the figure. Today let’s concentrate on a single axis, and in particular on the most important line properties like color, width and style.
To set line properties we pass appropriate arguments to the plotting method.
And now let’s create a simple example on which I’ll demonstrate line properties:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y1 = x - 5
y2 = x
y3 = x + 5
y4 = x + 10
y5 = x + 15
fig, ax = plt.subplots()
ax.plot(x, y1)
ax.plot(x, y2)
ax.plot(x, y3)
ax.plot(x, y4)
ax.plot(x, y5)
Here we have five simple linear functions plotted on one axes. We didn’t set the colors, so they were picked for us. Speaking of which… How do we set line colors?
LINE COLOR
We just set the color keyword argument to a color that we want the line to be drawn in:
fig, ax = plt.subplots()
ax.plot(x, y1, color='green')
ax.plot(x, y2, color='blue')
ax.plot(x, y3, color='red')
ax.plot(x, y4, color='yellow')
ax.plot(x, y5, color='gray')
LINE WIDTH
The next property I’d like to talk about is line width. You may want the more important lines to be thicker than the less important ones.
The line width is just a float number. Let’s add some line widths to our lines:
fig, ax = plt.subplots()
ax.plot(x, y1, linewidth=.5)
ax.plot(x, y2, linewidth=1)
ax.plot(x, y3, linewidth=2)
ax.plot(x, y4, linewidth=4)
ax.plot(x, y5, linewidth=10)
LINE STYLE
The next property is line style. By default the line is drawn as a solid line, but there are more styles available. Have a look:
fig, ax = plt.subplots()
ax.plot(x, y1, linestyle='solid')
ax.plot(x, y2, linestyle='dashed')
ax.plot(x, y3, linestyle='dotted')
ax.plot(x, y4, linestyle='dashdot')
ax.plot(x, y5, linestyle='solid')
Here’s the video version of this article: