Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually-defined axis labels for Matplotlib imshow()

The following code:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(0, 100, size=(10, 10))
plt.imshow(data, cmap='jet', interpolation='nearest')
plt.show()

Gives the following figure:

enter image description here

However, instead of the axis labels corresponding to the index in the array, I want to manually define them. For example, instead of the axis labels being (0, 2, 4, 6, 8) as above, I want them to be (0, 10, 20, 30 ...).

Here is the code I have tried for this:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(0, 100, size=(10, 10))
labels = range(0, 100, 10)
plt.imshow(data, cmap='jet', interpolation='nearest')
plt.xticks(labels)
plt.yticks(labels)
plt.show()

However, this gives the following figure:

enter image description here

How can I achieve a figure with an appearance like the first one, but with axis labels like the second one?

like image 598
Karnivaurus Avatar asked Oct 22 '15 14:10

Karnivaurus


People also ask

What is PLT Imshow ()?

imshow. The matplotlib function imshow() creates an image from a 2-dimensional numpy array. The image will have one square for each element of the array. The color of each square is determined by the value of the corresponding array element and the color map used by imshow() .


2 Answers

The best way to do this is to modify the extent values in argument of your imshow :

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(0, 100, size=(10, 10))
plt.imshow(data, cmap='jet', interpolation='nearest', extent=[0, 100, 0, 100])
plt.show()
like image 57
y3t1 Avatar answered Oct 09 '22 11:10

y3t1


Define your axes and modify the xticklabels, not the axis itself. Something like this:

fig, ax1 = plt.subplots(1,1)
data = np.random.randint(0, 100, size=(10, 10))
ax1.imshow(data, cmap='jet', interpolation='nearest')
ax1.set_xticklabels(['', 0,10,20,30,40])
like image 24
iayork Avatar answered Oct 09 '22 10:10

iayork