1

I am working on Python with the matplotlib library and I have a problem with color maps dimension.

I have some target variable target that depends on two variables x and y - i.e. my data target is a matrix with the variable x being rows and y columns. I want to represent target in a color map with respect to x and y. The problem is that I have more values for x than for y, hence if I plot a color map I get a rectangle - a rather ugly one because I have many more values for x than for y.

I would rather have rectangular "pixels" in the color map and a square map, rather than square "pixels" but a rectangular color map - or at least I would like to compare the two visualizations.

My question is: how can I force the color map to be square?

This is my current code - the cmap variable simply allows me to define my custom color scale:

import matplotlib.pyplot as plt
import matplotlib.pyplot as clr

target = ...

cmap = clr.LinearSegmentedColormap.from_list('custom blue', 
                                             ['#DCE6F1','#244162'],
                                             N=128)
plt.matshow(target, cmap=cmap)
plt.colorbar(cmap='custom blue')
Daneel Olivaw
  • 2,077
  • 4
  • 15
  • 23

2 Answers2

2

What's your matplotlib version? If it's newer than 1.1.0 then you can try this:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.rand(32, 64), cmap='rainbow', aspect=2)
plt.show()

enter image description here

This gives you rectangular pixels with square figure shape. You should replace np.random.rand(32, 64) by your data, and define the aspect ratio you like. Also, please refer to this post. There are other solutions you might be interested in.

Community
  • 1
  • 1
Andreas Hsieh
  • 2,080
  • 1
  • 10
  • 8
1

Andreas's answer works on my computer. You might see a slightly different result that with your code because imshow() will by default interpolate the image, therefore the picture will be different compared to matshow(). But the aspect parameter works on both. So either feed it to matshow(), or disable the interpolation in imshow():

fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(np.random.rand(32, 64), cmap='rainbow', aspect=2)
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.rand(32, 64), cmap='rainbow', aspect=2, interpolation="None")
plt.show()
Borja
  • 1,411
  • 11
  • 20