Search code examples
pythonmatplotlibcolorbar

How to close gap between python contour plot and colorbar


I have made a contour plot and set plt.axis = 'square'. This has caused a significant gap between the plot and the color bar. I have been struggling to find a way to close this gap. How can you choose the distance between a contour plot and its color bar? How can you close this gap up to the point that they are touching?

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
plt.contourf(data)
plt.colorbar()
plt.xlabel('y label')
plt.ylabel('x label')
plt.axis('square')

Solution

  • You can simply use the pad attribute of plt.colorbar, and set it to -0.2 to align it with the plot itself. In case you want the colorbar bigger/smaller, you can also use the shrink attribute. More info here.

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
    plt.contourf(data)
    plt.colorbar(pad = -0.2)
    
    plt.xlabel('y label')
    plt.ylabel('x label')
    plt.axis('square')
    

    Output:

    enter image description here