HOWTO · Matplotlib
How to Draw an Arbitrary Line in Matplotlib
Draw finite line segments in Matplotlib with plot(), hlines(), vlines(), and LineCollection.
On this page
To draw one finite line segment in Matplotlib, pass its two endpoint coordinates to Axes.plot(). Use hlines() or vlines() when the segment is horizontal or vertical, and use LineCollection when you have many independent segments. These APIs use data coordinates; axhline(), axvline(), and axline() solve a different, axes-spanning or infinite-line problem.
The examples use Python with Matplotlib. Install Matplotlib with python -m pip install matplotlib if it is not already available. Each runnable example saves a PNG so that it can be checked in a non-interactive environment; replace savefig() with plt.show() when you want an interactive window.
Draw a Finite Segment With plot()
For a segment from (x1, y1) to (x2, y2), give plot() one two-item sequence of x values and one two-item sequence of y values. Matplotlib connects values at the same positions, so the first x/y pair is one endpoint and the second pair is the other.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([3, 5], [1, 6], color="tab:green", marker="o")
ax.set(xlabel="x", ylabel="y", title="Finite segment with plot()")
fig.savefig("plot-segment.png", dpi=120)
print("saved: plot-segment.png")
saved: plot-segment.png
The marker makes the two endpoints visible. Add more paired values only when you intend to make a polyline: plot() connects consecutive points rather than creating unrelated segments.
Draw Finite Horizontal or Vertical Segments
Use hlines(y, xmin, xmax) for a horizontal segment and vlines(x, ymin, ymax) for a vertical segment. The coordinate held constant is the first argument; the other two arguments are the finite endpoints in data coordinates.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.hlines(3, 2, 5, color="tab:red")
ax.vlines(6, 1, 5, color="tab:green")
ax.set(xlim=(0, 7), ylim=(0, 6), xlabel="x", ylabel="y")
fig.savefig("horizontal-vertical-segments.png", dpi=120)
print("saved: horizontal-vertical-segments.png")
saved: horizontal-vertical-segments.png
Here the red segment runs from (2, 3) to (5, 3), while the green segment runs from (6, 1) to (6, 5). Explicit limits make the intended data range clear and avoid interpreting a clipped line as a shorter segment.
Do Not Substitute an Axes-Spanning Reference Line
axhline() and axvline() are useful reference lines, but they span the axes in one direction rather than using two data-coordinate endpoints. Likewise, axline() represents an infinite line through points or with a slope. Use one of those APIs only when that behavior is what the chart needs.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
segment = ax.hlines(3, 2, 5, color="tab:red")
reference = ax.axhline(3, color="0.35", linestyle="--")
assert segment.get_segments()[0].tolist() == [[2.0, 3.0], [5.0, 3.0]]
assert reference.get_transform() is ax.get_yaxis_transform()
print("hlines endpoints: [2.0, 3.0] to [5.0, 3.0]")
print("axhline uses axes-relative x coordinates")
hlines endpoints: [2.0, 3.0] to [5.0, 3.0]
axhline uses axes-relative x coordinates
The assertion demonstrates the boundary: hlines() retains finite data endpoints, whereas axhline() uses axes-relative coordinates for its horizontal extent. That distinction matters when zooming, changing limits, or exporting a plot.
Draw Many Independent Segments With LineCollection
When you need many disconnected segments, create a LineCollection from a sequence of two-point segments and add it to an axes. Calling autoscale() after add_collection() lets the axes include the collection; set explicit limits instead when a fixed viewing range is part of the chart.
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
segments = [[(1, 10), (6, 9)], [(1, 7), (3, 6)]]
collection = LineCollection(segments, colors=["tab:red", "tab:green"])
fig, ax = plt.subplots()
ax.add_collection(collection)
ax.autoscale()
ax.set(xlabel="x", ylabel="y", title="Two independent segments")
fig.savefig("line-collection.png", dpi=120)
print("segments: 2")
print("saved: line-collection.png")
segments: 2
saved: line-collection.png
LineCollection is a good fit for many segments because it groups them in one collection. It does not connect the end of one segment to the start of the next, which is the key difference from passing a longer point sequence to plot().
Choose the API That Matches the Geometry
Choose plot() for one segment or a connected path, hlines() and vlines() for finite axis-aligned segments, and LineCollection for a batch of disconnected segments. Prefer axhline() or axvline() only for an axes-spanning guide, and remember that axline() is infinite.
For parameter details and styling options, consult the official plot() documentation, hlines() documentation, vlines() documentation, and LineCollection documentation. The examples above were executed with Matplotlib 3.11.2 in the recorded local Polyglot container.