Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

How to Draw Horizontal Lines in Matplotlib

Use Matplotlib’s axhline for an Axes-spanning reference line and hlines for data-coordinate endpoints or multiple horizontal lines.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use ax.axhline(y=value) for a horizontal reference line that spans the whole Axes or a fraction of it. Use ax.hlines() when the line’s start and end should be specified as x-values in your data.

Draw a horizontal reference line across an Axes

ax.axhline() is the usual choice for a threshold, target, or baseline that should extend across the plot area. The y position is a data value; by default, the line spans the full Axes width.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [1, 3, 2])
ax.axhline(y=2, color="red", linestyle="--", linewidth=1.5)
plt.show()

In this example, the line marks y = 2. To draw it across only part of the Axes, set xmin and xmax to fractions of its width: 0 is the left edge and 1 is the right edge. For example, ax.axhline(y=2, xmin=0.25, xmax=0.75) spans the middle half of the Axes. These arguments are not x-values from your plotted data. See the Matplotlib axhline API documentation.

Choose between axhline and hlines

The deciding factor is how you want to specify the horizontal endpoints:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Relaxweex 1 Pcs 39.37" Flexible Magnetic Ruler Dual Scale Tape, White
  • Ample Quantity: our magnetic measuring tape comes in 1 roll, with dual units marked in centimeters and inches, satisfying your suitable measuring needs; Before placing an order, please note that due to the cold weather, PVC and magnets will shrink, resulting in a shorter size of our product, you can try soaking in hot water to see if it can be restored
  • Ideal Size: the magnetic ruler, with its width of about 1.18 inches and a length of approximately 39.37 inches/ 1 meter, is tailored right to fit customer needs; Its ideal size detailing allows it to be applied extensively without worrying about size issues
  • Quality Materials: constructed using soft magnets and PVC, the flexible magnetic ruler provides solid, firm attachment to most metallic surfaces; Please note that the product is isotropic magnetic material, with different adhesion capabilities for items made of different metal materials, and can be firmly adhered to iron products
  • Precision and Clarity: the magnetic flexible ruler comes with high precision and clearly marked measurements, more accurate precision; It has two different scales, metric and inch scales, and the markings are large and clear for easy reading
  • Multipurpose Utility: the magnetic ruler exhibits versatility, making it a valuable tool for workbenches, large whiteboards, drawing tables, tear fences, craft tables, T tracks or other places; Also, its easy roll up design makes them storage friendly
What you need Method Coordinates Returns
A single reference line across all or part of the Axes ax.axhline(y=...) y is a data value; xmin and xmax are Axes-width fractions Line2D
A finite segment with data-coordinate x endpoints ax.hlines(y, xmin, xmax) y, xmin, and xmax are data values LineCollection
Several horizontal lines ax.hlines(ys, xmins, xmaxs) Positions and endpoints can be scalar or array-like LineCollection

For example, this draws a segment at y = 2 from data x-value 0.5 to 1.5:

ax.hlines(y=2, xmin=0.5, xmax=1.5, colors="tab:blue", linestyles="dashed")

With several levels, pass a sequence for y; scalar endpoints can be shared across the lines. If you also pass arrays for the endpoints, check that their shapes and ordering pair each endpoint with the intended line. The hlines API documentation describes its arguments and return value.

Rank #2
Sale
Frienda 12 Inch Plastic Rolling Ruler Parallel Drafting Ruler
  • Wide applications: versatile measuring ruler, with a protractor to draw the desired figure, can also draw arc curve, horizontal parallel line, vertical parallel line, enough size for drawing
  • More details: each centimeter has a circle hole for drawing circles and ellipses; This drawing ruler is built in roller, clear scale, easy sliding, stable drawing, not easy to skew, clear scale, easy to observe; There are various formulas on the roller, which can be calculated quickly in use
  • Multiple uses: whether you are an artist, pattern maker or designer, this measuring rolling ruler is a good helper for your work or study; It can help you develop your own manual skills as well as your imagination to draw different design pictures
  • Quality material: our measuring ruler tool is made of transparent plastic; It is light-weighted, easy to carry; Transparent material allows you to draw without ignoring some important figures or words
  • Practical gift: the plastic ruler can be an ideal gift for your friends, family and artists in your life, the practical tool can bring them lots of conveniences and further enhance their creativity

Style or move the line

axhline accepts line properties including color, linewidth, linestyle, alpha, and zorder. For instance, the first example uses a red dashed line with a width of 1.5.

Because axhline returns a Line2D, you can keep the returned artist and change its y position later by setting both y values:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
MeasureMate Learning Ruler, Four-Sided Math Tool for Students, Teaching Number Lines, Fraction Line, with Metric and Imperial, Black, 2-Pack
  • Dynamic number line to improve math fluency and aid visual learners with integer markings ranging from -15 to 15
  • Simplify fraction counting using 0/12 to 12/12 markings, plus additional benchmark fractions (1/6, 1/4, 1/3, 1/2)
  • With a standard length of 12" (imperial) and 30.5cm (metric), this educational tool offers the convenience of a typical ruler, along with bonus math advantages!
  • Squared-off edges ensure effortless drawing of straight lines to create neat and precise diagrams, graphs, geometric shapes, and more.
line = ax.axhline(y=2)
line.set_ydata([3, 3])

hlines returns a LineCollection, not a Line2D; use the collection’s properties when styling or updating lines created with that method. Matplotlib’s Axes API documentation covers Axes artists and methods.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep coordinate systems straight

The key distinction is that axhline mixes coordinate systems: its y position is in data coordinates, while its horizontal extent is measured as fractions of the Axes width. With hlines, the y position and both x endpoints are data coordinates.

Rank #4
Westcott Acrylic Data Highlight Reading Ruler With Tinted Guide, 15" Clear
  • Ruler Reading Focus with Tinted Guide - Reading ruler features a tinted guide that highlights a single line, reducing eye strain and boosting reading accuracy when reviewing digital documents, notes, and diagrams for study and drafting
  • Dual Scales for Imperial and Metric - This dual-scale instrument serves as a classroom essentials tool, offering imperial and metric readouts on a clear ruler surface for quick layout, accurate conversions, and reliable drafting projects
  • Precision Markings for Clarity - Precise numerals and graduations provide visibility on this instrument, turning everyday measurement into a school essentials ruler for designers, engineers, and students who demand accuracy in layouts and study work
  • Straight Edge for True Layout - With a straight edge for true lines, this tool improves alignment and confidence for school supplies for kids and professionals, delivering steady visuals and reliable grid references during drafting and note taking
  • Versatile Use Across Environments - Ideal for home, school, shop, or office, this 15-inch clear plastic ruler travels easily between projects, supports precise measurements, and keeps your workflow efficient in drafting, design, and study tasks

Matplotlib’s horizontal and vertical line gallery example also demonstrates using an axis transform when an extent should be tied to the plotted area rather than to data limits. That approach is useful when the line’s vertical coordinate should map to the Axes boundaries: in the illustrated transform, 0 maps to the bottom and 1 to the top.

Best Value
KEARING 8" & 20cm Pattern Grading Ruler - Clear 1.2mm Sandwich Line Scale
  • The Plastic Pattern Grading Ruler,8" or 20cm length & 2" width standard size
  • High Quality Plastic 1.2mm thick, flexible plastic construction.
  • Lightweight and clear for easy handling and accurate positioning
  • Zero centering scale for precise measurement and pattern adjustment.
  • Long-lasting sandwich printings, sandwich line to prevent numbers from rubbing off.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.