Draw multiple axhlines and axvlines in one function using Python & Matplotlib


The result is:

Draw multiple axhlines and axvlines in one function using Python and Matplotlib

This page shows how to draw multiple axhlines and axvlines in one function using python and matplotlib.

See also:

Python Matplotlib Tips: Convert x value to symlog scale with zero shift using Python and matplotlib.pyplot

This code shows how to convert x value to symlog scale with zero shift using Python and matplotlib.pyplot


Python Matplotlib Tips: Two ways to align ylabels for two plots using Python and matplotlib.pyplot

This page shows two ways to align two ylabels for two subplots using Python and matplotlib.pyplot.


Python Matplotlib Tips: One ylabel for two subplots using Python Matplotlib.pyplot

Learn how to draw one ylabel for two vertical subplots using python matplotlib.pyplot



In [1]:
import platform
print('python: '+platform.python_version())
import matplotlib.pyplot as plt
from matplotlib import __version__ as matplotlibversion
print('matplotlib: '+matplotlibversion)
import numpy as np
print('numpy: '+np.__version__)
pi = np.pi
python: 3.7.6
matplotlib: 3.1.3
numpy: 1.18.1
In [2]:
# sine and cosine dummy curve data to plot
xx  = np.linspace(0, 3.*pi)
yy1 = np.sin(xx)
yy2 = np.cos(xx)

Define axvlines and axhlines functions to plot multiple v-line(s) and h-line(s), respectively.

In [3]:
def axvlines(ax=None, xs=[0, 1], ymin=0, ymax=1, **kwargs):
    ax = ax or plt.gca()
    for x in xs:
        ax.axvline(x, ymin=ymin, ymax=ymax, **kwargs)

def axhlines(ax=None, ys=[0, 1], xmin=0, xmax=1, **kwargs):
    ax = ax or plt.gca()
    for y in ys:
        ax.axhline(y, xmin=xmin, xmax=xmax, **kwargs)

Keyward argments can be also used in above function as follows.

In [4]:
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)
ax1.plot(xx, yy1, c='b')
ax2.plot(xx, yy2, c='b')
axvlines(ax=ax1, xs=[0.0*pi, 1.0*pi, 2.0*pi], c='r', ls='--')
axvlines(ax=ax2, xs=[0.5*pi, 1.5*pi, 2.5*pi], c='g', ls='-.')
axhlines(ax=ax1, ys=[-1.0, 0.0, 1.0], c='k', lw=0.5)
axhlines(ax=ax2, ys=[-1.0, 0.0, 1.0], c='k', lw=0.5)
plt.savefig('ax_vh_lines.png', bbox_inches='tight', pad_inches=0.02)