2015-08-13 50 views
1

當在Matplotlib中使用imshow繪製矩陣時,如何更改colorbar legend大小,位置,字體和其他參數?如何更改顏色條以與Matplotlib中的主圖匹配?

在這裏,我創建了一個例子代碼

import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
%matplotlib inline 

def plot_matrix(mat, title='example', cmap=plt.cm.Blues): 
    plt.imshow(mat, interpolation='nearest', cmap=cmap) 
    plt.grid(False) 
    plt.title(title) 
    plt.colorbar() 

data = np.random.random((20, 20)) 

plt.figure(figsize=(8,8)) 
plt.tick_params(axis='both', which='major', labelsize=12) 

plot_matrix(data) 

enter image description here

在實際使用的情況下,我得到了複雜的標籤和圖例條變得更高,則矩陣本身。我想改變圖例欄以更有效地利用空間。

我發現爲matplotlib.pyplot.colorbar,但沒有找到一個好方法來設置彩色圖例欄的大小,位置和字體大小。

+1

你已經使用'make_axes_locatable'許多可能性使用,[如這裏詳細](http://stackoverflow.com/a/18195921/832621) –

+0

+1,'make_axes_locatable'方法計算繪圖時軸的位置和大小。或者,我們可以在繪製時間之前指定軸的位置和大小。見下: –

回答

2

imshow執行1:1方面(默認情況下,但您可以使用aspect參數更改它),這會使事情變得有點棘手。要始終獲得一致的結果,我可能會建議手動指定軸的尺寸:

import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
%matplotlib inline 

def plot_matrix(mat, figsize, title='example', cmap=plt.cm.Blues): 
    f = plt.figure(figsize=figsize) 
    ax = plt.axes([0, 0.05, 0.9, 0.9 ]) #left, bottom, width, height 
    #note that we are forcing width:height=1:1 here, 
    #as 0.9*8 : 0.9*8 = 1:1, the figure size is (8,8) 
    #if the figure size changes, the width:height ratio here also need to be changed 
    im = ax.imshow(mat, interpolation='nearest', cmap=cmap) 
    ax.grid(False) 
    ax.set_title(title) 
    cax = plt.axes([0.95, 0.05, 0.05,0.9 ]) 
    plt.colorbar(mappable=im, cax=cax) 
    return ax, cax 

data = np.random.random((20, 20)) 
ax, cax = plot_matrix(data, (8,8)) 

現在你已經在彩條的繪製,cax軸。你可以做很多事情與,說,旋轉標籤,plt.setp(cax.get_yticklabels(), rotation=45)

enter image description here

+0

謝謝CT!我遵循你的方式來實現我的方法,它完美地工作。酒吧的大小很好。我也可以在創建它們時設置x和y刻度的字體大小。另一件事我也想設置colorbar標籤的字體。有什麼建議麼? – Bin

+0

歡迎您!更改字體爲:'假設您的盒子上安裝了'Time New Roman',則爲'plt.setp(cax.get_yticklabels(),fontname ='Times New Roman') '。 –

相關問題