Add a white background to colorbar in matplotlib

Viewed 3423

I would like to make my colorbar more visible by adding a white background. I need the colorbar inside the image, which makes it hard to read at times.

Here is the code without the white background.

import matplotlib.pyplot as plt
import numpy as np

a=np.random.rand(10,10)

fig=plt.figure()
ax=fig.add_axes([0,0,1,1]) #fill the entire axis
im=ax.imshow(a)
cbaxes=fig.add_axes([0.8,0.1,0.03,0.8]) #add axis for colorbar, define size
cb=fig.colorbar(im,cax=cbaxes) #make colorbar
#cb.outline.set_color('white') #this does not work
fig.show()
3 Answers

Note that since @Hagne posted their answer the API has changed for turning off tick markers.

You now need to pass False, rather than off. This caught me out for a while as the API didn't complain - just didn't work

cbbox.tick_params(
    axis = 'both',
    left = False,
    top = False,
    right = False,
    bottom = False,
    labelleft = False,
    labeltop = False,
    labelright = False,
    labelbottom = False
)
Related