Bin
Bin

Reputation: 3834

How to change color bar to align with main plot in Matplotlib?

When plotting matrix with imshow in Matplotlib, how to change colorbar legend bar size, location, font and other parameters?

Here I created an example code

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

In a real use case, I got complex labels and the legend bar becomes much higher then the matrix itself. I want to change the legend bar to make the plot more efficiently use the space.

I found a documentation for the matplotlib.pyplot.colorbar, however have not figure out a good way to set the size, location and font size for the color legend bar.

Upvotes: 2

Views: 4938

Answers (1)

CT Zhu
CT Zhu

Reputation: 54380

imshow enforces a 1:1 aspect (by default, but you can change it with aspect parameter), which makes things a little trickier. To always get consistent result, I might suggest manually specify the size of axes:

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

Now you have the axis where the colorbar is plotted in, cax. You can do a lot of thing with that, say, rotate the labels, using plt.setp(cax.get_yticklabels(), rotation=45)

enter image description here

Upvotes: 3

Related Questions