1

I am trying to plot matshow with aspect ratio 1, but when I rely on the method suggested here I get an extra space around the plot that I cannot get rid off. What is the solution?

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import ticker
def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
a=np.random.randn(8,4)
plt.matshow(a)
plt.colorbar(shrink=.5)
ax=plt.gca()
forceAspect(ax,aspect=1)
plt.xticks(np.arange(0, 4, 1), np.arange(1, 5, 1))
plt.yticks(np.arange(0, 8, 1), np.arange(1, 9, 1))
#plt.tight_layout()
#ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1d'))
#ax.xaxis.set_ticks(np.arange(1, 6, 1))
plt.show()

enter image description here

Community
  • 1
  • 1
Cupitor
  • 11,007
  • 19
  • 65
  • 91

1 Answers1

1

So, as I understand it, you want two things: 1. adjust the height of the colorbar to match the hight of the plot and change the size of the figure such that there is not too much empty space around it. The first thing is relatively easy to achieve. For the second one I believe that you have to specify the figure size manually.

import numpy as np
from matplotlib import pyplot as plt

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

a=np.random.randn(8,4)
fig = plt.figure(1, figsize=(5,4))
plt.matshow(a,fignum=1)
ax=plt.gca()
forceAspect(ax,aspect=1)
plt.xticks(np.arange(0, 4, 1), np.arange(1, 5, 1))
plt.yticks(np.arange(0, 8, 1), np.arange(1, 9, 1))
cbar = plt.colorbar()
plt.draw()
pos_cbar = cbar.ax.get_position()
pos_ax = ax.get_position()
pos_cbar.y0 = pos_ax.y0
pos_cbar.y1 = pos_ax.y1
cbar.ax.set_position(pos_cbar)

plt.show()
hitzg
  • 12,133
  • 52
  • 54
  • Thank you very much. I couldn't get rid of the extra space using `fig.set_size_inches` do you have any ideas? – Cupitor Dec 01 '14 at 13:00
  • Never mind. Found the solution: http://stackoverflow.com/questions/4042192/reduce-left-and-right-margins-in-matplotlib-plot – Cupitor Dec 01 '14 at 13:02
  • Yes, I came across that problem too. That is why I've set the figure size upon creating it. Cool that you have found a better solution to that part! – hitzg Dec 01 '14 at 13:13