pythonmatplotlib

Plot Constant Function in Python


I want to plot some constant functions (horizontal lines) like y=2 and y=5 all in the same plot.

Also, I need to set each axes scale (like x going from 0 to 1 and y from 0 to 20). I need to do the same for x=5 and x=2 (vertical lines) in another plot, but I guess the process should be similar

Here's an image of how the horizontal lines should look (in this case without axes scale)enter image description here


Solution

  • hlines is what you are looking for, try the code below

    fig,ax = plt.subplots(figsize=(12,6))
    
    ax.set_ylim(-1,20)
    ax.set_xlim(-10,10)
    
    ax.hlines(3,-15,15,color='b')
    ax.hlines(5,-15,15,color='b')