Harpal
Harpal

Reputation: 12577

matplotlib: colour bar resizing image?

I'm assuming I have a really simple question, which has been driving me insane for the past hour. So, I am trying to produce a contour plot with the following axis lengths x=37,y=614. I can produce a contour plot no problem, but when I add a colour bar the image becomes resized to what i'm assuming is the size of the colour bar.

Image without colour bar:

enter image description here

Image with colour bar: enter image description here

The figure becomes resized and I do not know why. How can I plot a figure like my first figure but with the colour scheme of the second figure and with a colour bar?

code:

import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from matplotlib import pylab


y = np.arange(1, 615)
x = np.arange(1, 37)

z = np.loadtxt('145_contact_matrix_605.txt')


fig = plt.figure()
ax = plt.subplot(111)
CS = ax.contour(x, y, z)
plt.clabel(CS, inline=1, fontsize=10)


# COLOUR BAR CODE
im_out = ax.imshow(z, cmap=cm.jet)
ax.matshow(z,cmap=plt.cm.jet)
axcolor = fig.add_axes([0.9,0.1,0.02,0.8]) # adjust these vaules to position colour bar
pylab.colorbar(im_out, cax=axcolor)

plt.show()

Upvotes: 1

Views: 585

Answers (1)

Joe Kington
Joe Kington

Reputation: 284582

It's the imshow command that's changing the aspect ratio of the axes, not the colorbar.

imshow assumes you want an aspect ratio of 1.0 so that a square in data coordinates will appear square (i.e. square pixels).

If you want it to behave like contour, the just specify aspect='auto'.

ax.imshow(z, cmap=cm.jet)

You should also remove the ax.matshow line (or use it instead of imshow). As it is, you'll have two images that partially overlap and hide each other.

If you do decide to use matshow instead of imshow, you'll need to specify aspect='auto' for it, as well.

Upvotes: 1

Related Questions