2015-08-13 49 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') '。 –

相关问题