Explain Codes LogoExplain Codes Logo

Plot a horizontal line on a given plot

python
matplotlib
plotting
data-visualization
Anton ShumikhinbyAnton Shumikhin·Dec 20, 2024
TLDR

To draw a horizontal line on your plot, use matplotlib's plt.axhline() function:

import matplotlib.pyplot as plt # Let's suppose you've already plotted something # plt.plot(...) plt.axhline(y=<value>, color='<color>', linestyle='<style>') plt.show()

In the above code, replace <value> with the y-axis value where you want the line, <color> with any color of your choice (e.g., 'r' for red), and <style> with the line style (e.g., '--' for dashed). This way you can add a styled horizontal line at a specific y value.

Leveling up from the basics

Drawing a horizontal line may seem simple, but there is more than meets the eye. Let's dive deeper into this and demystify the secrets!

How to customize the line

The wonderful thing about the function plt.axhline() is that it can be utilized with any plot type. If you are used to creating plots using objects, the method ax.hlines() offers enhanced control over your line:

fig, ax = plt.subplots() ax.hlines(y=2.5, xmin=0, xmax=10, colors='green', linestyles='dashdot') # We are ecofriendly coders, even our code is 'green'

Drawing lines in time series and bar charts

Time series and bar charts come with their unique considerations. In a time series, ensure the xmin and xmax parameters handle datetime objects, aligning your horizontal line with the correct time intervals.

With bar plots, align xmin and xmax with bars accurately. Typically, setting them according to the bar indices rather than physical coordinates or tick labels yields the best results.

Scaling heights with pandas and seaborn

When using Pandas DataFrames, you can chain the .axhline() method after your plotting command:

df.plot(kind='line') plt.axhline(y=2.5, color='purple', linestyle='-') # Purple rain, purple line...

Besides, Seaborn allows you to add horizontal lines easily, enhancing the sophistication of your visualization.

Smoothening the rough edges

Smooth operator

Being a smooth operator is not just for Sade; your lines might need to be, too. When your line must indicate a trend or pattern, consider using UnivariateSpline from the scipy library with a numpy array to map values smoothly.

Clear comments

It's good practice to comment your code, especially in complex plots. This ensures your code remains transparent for future reference or for any other pair of eyes checking your code - be kind to your future self and teammates!

Don't stretch it

Always ensure the y-axis limits are correctly set to accommodate your horizontal lines. Use pylab.ylim() or set_ylim() method on an axes object. Your plot's visibility and readability should be your top priority.

Try these tips and tricks

Multiple lines

Don't hesitate to add multiple horizontal lines - they can represent different threshold levels or significant values. Pass a list of y-values to matplotlib.pyplot.hlines:

plt.hlines(y=[1.5, 2.5, 3.5], xmin=0, xmax=len(data)-1, colors=['pink', 'red', 'maroon']) # Forget traffic lights, here are your data stoplights!

Special consideration

For a dataset with a varying x-axis range, consider creating a numpy array sized appropriately to represent xmin and xmax values.

Get some guidance

If you're looking for more custom solutions, matplotlib's official documentation and additional resources listed below house a plethora of examples, tips, and advice for almost any situation.