Search code examples
pythonmatplotlibplotvisualization

Matplotlib axhline: linewidth changes X position of line


I've observed some weird effects of using linewidth param in axhline from matplotlib.pyplot. I want to make line bolder, but this param makes line wider too.

For example, linewidth = 1: enter image description here

and linewidth = 25: enter image description here

X position of these blocks makes really big difference for me. I can't accept errors as big as that. Do you have any ideas how to make this line bolder without changing their X position?


Solution

  • If the lines you are drawing are limited between a minimum and a maximum value, then you should use matplotlib.pyplot.hlines in place of matplotlib.pyplot.axhline. Moreover you can control the line endings style with capstyle parameter:

    import matplotlib.pyplot as plt
    
    
    fig, ax = plt.subplots()
    
    ax.hlines(y = 1, xmin = 1, xmax = 2, color = 'red', linewidth = 1, label = 'linewidth = 1, default capstyle')
    ax.hlines(y = 2, xmin = 1, xmax = 2, color = 'green', linewidth = 25, capstyle = 'projecting', label = 'linewidth = 25, "projecting" capstyle')
    ax.hlines(y = 3, xmin = 1, xmax = 2, color = 'blue', linewidth = 25, capstyle = 'butt', label = 'linewidth = 25, "butt" capstyle')
    
    ax.set_xlim(-1, 4)
    ax.set_ylim(-1, 5)
    
    ax.legend(frameon = True)
    
    plt.show()
    

    enter image description here