Plot a horizontal line on a given plot
To draw a horizontal line on your plot, use matplotlib's plt.axhline()
function:
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:
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:
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
:
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.
Was this article helpful?