Customizing Line Plots
A line plot is one artist with a long vocabulary of visual properties: color, line style, line width, markers at the data points, and a label for the legend. Matplotlib exposes all of them as keyword arguments to plot, as a compact format string, or after the fact on the returned Line2D object. This chapter covers the full set, because line charts are the most common chart and these knobs are used in every one of them.
The Format String
The first positional argument of plot can be a shorthand string combining color, linestyle, and marker: plot(x, y, "r--o") is a red dashed line with circle markers.
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(x, y, "r--o") # red, dashed, circle markers
plt.show()
Components: colors are r, g, b, c, m, y, k, w; linestyles are - solid, -- dashed, -. dash-dot, : dotted; markers are o, s, ^, D, *, p, and more. Compact for exploration, but opaque in production code - keywords are clearer.
Keyword Arguments
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(x, y,
color="#2563eb", # hex, name, tuple, or any CSS color
linestyle="--",
linewidth=2.0,
marker="o",
markersize=7,
markerfacecolor="white",
markeredgecolor="#2563eb",
markeredgewidth=1.5,
alpha=0.9,
label="squares")
plt.show()
Colors accept hex strings, named colors, RGBA tuples, or colormap values - the colors chapter goes deeper. alpha sets transparency for the whole line. Every property has a corresponding set_* method on the returned line for post-hoc changes.
Modifying After the Fact
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
fig, ax = plt.subplots()
(lines,) = ax.plot(x, [v * v for v in x])
lines.set_linestyle(":" )
lines.set_color("tab:green")
lines.set_markersize(10)
lines.set_label("updated")
ax.legend()
plt.show()
plot returns a list of Line2D objects; unpacking it gives you the artist to configure imperatively. This is how you apply a shared style to many series, or restyle a line after data is loaded.
Dashed Patterns and Z-Order
- Custom dash patterns:
linestyle=(0, (5, 2, 1, 2))- a tuple of (offset, on/off segments in points) for precise control. zordercontrols stacking: later-drawn lines are on top by default; setzorderto pin a reference line above data lines.solinewidthand marker properties are independent - a thick line with tiny markers is a common emphasis style.
Summary
Style lines with the format string for speed and with keywords for clarity: color, linestyle, linewidth, markers, alpha, and label all take one argument. When you need to change many lines at once, unpack the returned Line2D objects and call their set_* methods - the artist is the source of truth either way.