在matplotlib中为colorbar添加白色背景

Wes*_*ten 4 python matplotlib

我想通过添加白色背景使我的颜色条更加醒目.我需要图像中的颜色条,这使得有时难以阅读.

这是没有白色背景的代码.

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()
Run Code Online (Sandbox Code Playgroud)

Sue*_*ver 7

The colorbar is a patch so you will want to set the edge color to be white. The reason that set_color didn't work is because it sets both the face and edge color to white.

cb.outline.set_edgecolor('white')
cb.outline.set_linewidth(2)
Run Code Online (Sandbox Code Playgroud)

If you want the labels to also be white, you will want to set the tick parameters for those.

cbaxes.tick_params(axis='both', colors='white')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Hag*_*gne 6

这是创建背景的解决方案:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述