pythonmatplotlibcolorbar

Adding lines to colorbar in matplotlib that are longer than the colorbar


This is a follow-up question to

Adding markers or lines to colorbar in matplotlib

I would like to indicate positions on a colorbar that extends over the length/width of the colorbar itself.

In the optimal case, I would like to add a label to that line.

I tried matplotlib.pyplot.hlines as well as matplotlib.axes.Axes.axhline and simply adding a line using matplotlib.axes.Axes.plot adjusting the xmin and xmax-values but nothing let me extend over the boundaries of the colorbar.

That is (modifying the example from the stackoverflow post cited above), I would like to have something like the red horizontal line on the colorbar:

enter image description here


Solution

  • As in the answer to this question, you can use clip_on=False to allow things to extend beyond the axes limits, e.g., (following the question you link to):

    import matplotlib.pyplot as plt
    import numpy as np
    
    vals = np.linspace(-np.pi/2, np.pi/2, 101)
    x, y = np.meshgrid(vals, vals)
    
    z = np.abs(np.sinc(x) * np.sinc(y))
    
    xDeg = np.rad2deg(x)
    yDeg = np.rad2deg(y)
    
    plt.pcolormesh(xDeg, yDeg, z, cmap='jet', vmin=0, vmax=1)
    cb = plt.colorbar()
    
    plt.axis([-90, 90, -90, 90])
    ticks = np.linspace(-90, 90, 13)
    plt.xticks(ticks)
    plt.yticks(ticks)
    
    # add red line over colour bar (note: zorder defines the order with
    # which something is added to the plot, i.e., things with larger
    # numbers are added later so appear on top of previously added objects)
    cb.ax.plot([-0.5, 1.5], [0.4, 0.4], color="r", lw=4, clip_on=False, zorder=100)
    

    enter image description here