繁体   English   中英

在 matplotlib 中为颜色条添加白色背景

[英]Add a white background to colorbar in 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()

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

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()

在此处输入图片说明

colorbar是一个patch ,所以你将要设置的边缘颜色为白色。 其原因set_color没有工作,是因为它设置面和边缘的颜色为白色。

cb.outline.set_edgecolor('white')
cb.outline.set_linewidth(2)

如果您希望标签为白色,则需要为这些标签设置刻度参数。

cbaxes.tick_params(axis='both', colors='white')

在此处输入图片说明

请注意,自从@Hagne 发布他们的答案后,API 已更改为关闭刻度标记。

您现在需要传递False ,而不是off 这让我抓了一阵子,因为 API 没有抱怨 - 只是没有用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM