Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a white background to colorbar in matplotlib

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()
like image 428
Wesley Kitlasten Avatar asked Mar 11 '16 21:03

Wesley Kitlasten


1 Answers

Here is a solution for creating the background:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

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

fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
im=ax.imshow(a)

cbbox = inset_axes(ax, '15%', '90%', loc = 7)
[cbbox.spines[k].set_visible(False) for k in cbbox.spines]
cbbox.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
cbbox.set_facecolor([1,1,1,0.7])

cbaxes = inset_axes(cbbox, '30%', '95%', loc = 6)

cb=fig.colorbar(im,cax=cbaxes) #make colorbar

fig.show()

enter image description here

like image 96
Hagne Avatar answered Oct 17 '22 19:10

Hagne