2

I would like to make a figure using imshow in matplotlib for which I can usefully set the width and height. I thought I could use figsize to do that, but it's performing the way I thought it would.

For example, using the following MWE:

import matplotlib.pyplot as plt
import numpy as np

N = 100
width = 20
height = 20
Z = np.random.random((width,height))

G = np.zeros((width,height,3))

# Here we set the RGB for each pixel
G[Z>0.5] = [1,1,1]
G[Z<0.5] = [0,0,0]

plt.figure(figsize = (2, 5))
plt.imshow(G,interpolation='nearest')
plt.grid(False)
plt.show()

Here is what I get:

enter image description here

If I change figsize = (2, 5) to figsize = (2, 2), for example, the proportions don't change!

After trying a few different values I think this is because the graph is being rendered as a box instead of as a rectangle: no matter what I set figsize to the individual matrix entries are a constant box.

Is there a command that I can use to e.g. tell matplotlib to expand out to e.g. 800x400px?

Aleksey Bilogur
  • 3,686
  • 3
  • 30
  • 57

1 Answers1

7

The default behavior of imshow is to set the aspect ratio of the host axes to be 'equal' (that is squares in data-units are squares in screen space). If you do not care about this, just set the aspect to 'auto'.

import matplotlib.pyplot as plt
import numpy as np


N = 100
width = 20
height = 20
Z = np.random.random((width, height))

G = np.zeros((width, height, 3))

# Here we set the RGB for each pixel
G[Z > 0.5] = [1, 1, 1]
G[Z < 0.5] = [0, 0, 0]

fig, ax = plt.subplots(figsize=(2, 5))
ax.imshow(G, interpolation='nearest')
ax.set_aspect('auto')
plt.show()
tacaswell
  • 84,579
  • 22
  • 210
  • 199