pythonmatplotlibhorizontal-line

How to make horizontal line stop at specific x-value?


I would like to draw a horizontal line with matplotlib's plt.axhline() function, but I want the horizontal line to stop at the absolute value of 5 on the x-axis. How do I set xmax in plt.axhline() to stop at 5?

plt.figure()
plt.plot(np.arange(-60, 60, 20), np.arange(0, 1.2, 0.2))
plt.axhline(y = 0.5, xmax = 5, c= 'r')

Solution

  • You need to use plt.hlines instead, also specify a xmin and change c to color .

    import matplotlib.pyplot as plt
    import numpy as np
    xmin = -65
    plt.figure()
    plt.plot(np.arange(-60, 60, 20), np.arange(0, 1.2, 0.2))
    plt.hlines(y = 0.5, xmin=xmin , xmax = 5, color= 'r')
    plt.xlim(left=xmin);