簡體   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