Reputation: 263
I created a simple heatmap with matplotlib with the following code:
fig,ax = plt.subplots(1)
# Display the image
ax.imshow(im)
a = np.array([[0.8, 2.4, 2.5, 3.9],
[2.4, 0.0, 4.0, 1.0],
[1.1, 2.4, 0.8, 4.3],
[0.6, 0.0, 0.3, 0.0],
[0.7, 1.7, 0.6, 2.6]])
ax1 = fig.add_subplot(111)
ax1.imshow(a, cmap='hot')
pos1 = ax1.get_position() # get the original position
pos2 = [0.13, 0.15, 0.3, 0.3]
ax1.set_position(pos2) # set a new position
This code works, the only problem is that i don't know how to make my heatmap wider. How can i set the width of an heatmap on MPL?
Upvotes: 1
Views: 1068
Reputation: 80459
The image can be positioned using the extent=[x0, x1, y0, y1]
parameter of imshow
. Without explicitly setting extent
, the x goes from -0.5
to width-0.5
. This puts the ticks at integer positions nicely in the center of the cells.
As imshow
resets the xlim to the last image drawn, these need to be set explicitly.
Optionally the aspect ratio can be set to 'auto' to make the image stretch with the dimensions of the surrounding figure.
from matplotlib import pyplot as plt
import numpy as np
fig, ax = plt.subplots(1)
# Display the image
im = np.random.randn(5, 10).cumsum(axis=0).cumsum(axis=1)
ax.imshow(im)
a = np.array([[0.8, 2.4, 2.5, 3.9],
[2.4, 0.0, 4.0, 1.0],
[1.1, 2.4, 0.8, 4.3],
[0.6, 0.0, 0.3, 0.0],
[0.7, 1.7, 0.6, 2.6]])
x0 = im.shape[1] - 0.5
x1 = x0 + a.shape[1]
ax.imshow(a, cmap='hot', extent=[x0, x1, -0.5, a.shape[0] - 0.5])
ax.set_xlim(-0.5, x1)
# ax.set_aspect('auto')
plt.show()
Upvotes: 2