How to change rescale tick label for imshow in python?

Question:

I am not able to change the tick labels. For example, I create a heatmap using imshow, and the indices for the heatmap don’t correspond to the intensity values. Here is a snippet of code to demonstrate my question:

iters=100
A=np.arange(0,iters+1)/(iters)
B=np.arange(0,iters+1)/(iters)
C = np.zeros((len(A),len(B)))
for i in range(0,len(A)):
    for j in range(0,len(B)):
        a = A[i]
        b = B[j]
        C[j][i]=a-b
        
fig, ax = plt.subplots()
img = ax.imshow(C, cmap='hot', interpolation='none')
plt.colorbar(img)
ax.invert_yaxis()
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_xticklabels(A)
ax.set_yticklabels(B)
plt.show()

The values for the X and Y axes in the plot should be labeled according to the values populated in A and B. If I set the ticks according to the arrays A and B, I only get the first few elements. How associate the tick labels with the full range of A and B?

Asked By: Ralff

||

Answers:

Better solution

No doubt the more elegant solution, as suggested in the comments.

import numpy as np
import matplotlib.pyplot as plt

iters=100
A=np.arange(0,iters+1)/(iters)
B=np.arange(0,iters+1)/(iters)
C = np.zeros((len(A),len(B)))

fig, ax = plt.subplots()
img = ax.imshow(C, cmap='hot', interpolation='none',
                extent=(A[0], A[-1], B[-1], B[0]))
plt.colorbar(img)
ax.invert_yaxis()
ax.set_xlabel('A')
ax.set_ylabel('B')

plt.show()

Original solution

I guess the use case for this solution would be when you want custom labels, for example:

labels=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]

for i in range(0,len(A)):
    for j in range(0,len(B)):
        a = A[i]
        b = B[j]
        C[j][i]=a-b
        
fig, ax = plt.subplots()
img = ax.imshow(C, cmap='hot', interpolation='none')
plt.colorbar(img)
ax.invert_yaxis()
ax.set_xlabel('A')
ax.set_ylabel('B')

ax.set_xticks(np.arange(0, 101, 10), labels)
ax.set_yticks(np.arange(0, 101, 10), B[0:101:10])

plt.show()

Using ax.set_xticks(np.arange(0, 101, 10), A[0:101:10]) you set the tick locations with np.arange(0, 101, 10), and then labels.

enter image description here

Answered By: plasma_r
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.