Search code examples
pythonmatplotlibline

How do I make a dashed horizontal line with matplotlib?


I want just a horizontal dashed line. If I was using pyplot.plot() I would add the argument '-' but I'm using axes.Axes.axhline() and it doesn't seem to recognize that as an argument, and I can't find a way to specify it in the documentation.


Solution

  • Here are two solutions. You may be confusing two different ways of interacting with matplotlib. It's important when reading the docs and examples that you know which method you want to use. More info is here: https://matplotlib.org/stable/tutorials/introductory/usage.html#the-object-oriented-interface-and-the-pyplot-interface

    Objected-Oriented Interface (this I prefer)

    Works by manipulating figure and axes objects. I find this gives me way more control over the plots.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.axhline(0.5, linestyle='--')
    

    Pyplot Interface

    This is how I initially learned matplotlib. You issue plt commands which add and change features.

    import matplotlib.pyplot as plt
    
    plt.subplots()
    plt.axhline(0.5, linestyle='--')
    

    horizontal line chart