Manually-defined axis labels for Matplotlib imshow()

北城余情 提交于 2021-02-04 17:20:09

问题


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:

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:

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


回答1:


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()



回答2:


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])


来源:https://stackoverflow.com/questions/33283601/manually-defined-axis-labels-for-matplotlib-imshow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!