Matplotlib imshow ticks are wrong with negative values

Viewed 19
import matplotlib.pyplot as plt
import numpy as np


a = np.random.randn(5,5)
plt.imshow(a)
plt.xticks(range(5))
plt.yticks([i-2 for i in range(5)])
plt.show()

results in

enter image description here

??

Also imagine I had 500 instead of 5 ticks, how could I pass the ticks but have less be displayed (for example every 10th)?

1 Answers

Use the extent parameter, and no need to use xticks or yticks:

plt.imshow(a, extent=(-0.5, 4.5, -2.5, 2.5))

Output:

enter image description here

Use MultipleLocator for your second question:

from matplotlib.ticker import MultipleLocator

a = np.random.randn(500,500)
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(a, extent=(-0.5, 500.5, -250.5, 250.5))
ax.xaxis.set_major_locator(MultipleLocator(25))
ax.yaxis.set_major_locator(MultipleLocator(25))

Output:

enter image description here

Related