Search code examples
pythonmatplotlibheatmap

Matplotlib heatmap axis labels not aligned correctly with cells


Here is the code I'm using for generating heatmap:

import numpy as np
import matplotlib.pyplot as plt

x_values = [x for x in range(5)]
y_values = [y for y in range(7)]
z_values = np.random.rand(len(y_values), len(x_values))
plt.imshow(z_values, cmap='viridis', extent=[min(x_values), max(x_values), min(y_values), max(y_values)],
           origin='lower', aspect='auto')

plt.gca().invert_yaxis()

# Add labels for every y-axis point and every second x-axis point
plt.yticks(np.arange(len(y_values)), y_values)
plt.xticks(np.arange(0, len(x_values), 2), x_values[::2])

plt.show()

This is example result:Generated heatmap

It is clear that the x-axis and y-axis labels are misaligned with the cel centers. How do I fix this?


Solution

  • Just change

    extent=[min(x_values), max(x_values), min(y_values), max(y_values)]
    

    to

    extent=[min(x_values), max(x_values) + 1, min(y_values), max(y_values) + 1]
    

    in the call to imshow.