matplotlib 中数组的可视化

Visualization of an array in matplotlib

我正在尝试使用 matplotlib(3.5 版本)在 Python 中可视化具有 (10, 10) 正方形的随机数组。我还包括 xaxis 和 yaxis 刻度,但 10 的刻度显示空数据。有人知道怎么解决吗?

这是我的代码:

import numpy as np

from matplotlib import pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'medium',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

arr = np.random.rand(10, 10)
plt.imshow(arr)
plt.ylim(0, 10)
plt.xlim(0, 10)

plt.xticks(np.arange(0.0, 11.0, 1.0))
plt.yticks(np.arange(0.0, 11.0, 1.0))

plt.show()

这是生成的图像:

正如其他用户指出的那样,Python 数组从“0”开始索引。你可以欺骗刻度来显示你想要的值:

  1. 创建要绘制的数据

    import numpy as np
    
    from matplotlib import pyplot as plt
    import matplotlib.pylab as pylab
    params = {'legend.fontsize': 'medium',
              'figure.figsize': (15, 5),
             'axes.labelsize': 'x-large',
             'axes.titlesize':'x-large',
             'xtick.labelsize':'x-large',
             'ytick.labelsize':'x-large'}
    pylab.rcParams.update(params)
    
    arr = np.random.rand(10, 10)
    
    
    
  2. 然后你可以使用 plt.xticks(tickPosition,tickValues) 和 yticks 一样。请注意,每个数字都指向图像中每个值的中心,因此您还必须更改 lim 位置:

    plt.figure()
    plt.imshow(arr)
    plt.ylim(-0.5, 9.5) #to show no blank spaces
    plt.xlim(-0.5, 9.5) #to show no blank spaces
    
    plt.xticks(np.arange(0, 10),np.arange(1, 11)) #trick the ticks
    plt.yticks(np.arange(0, 10),np.arange(1, 11))

这会给你下一个数字

  1. 你也可以在开始时设置值(左下角)只是稍微多一点:
    plt.xticks(np.arange(-0.5, 9.5),np.arange(1, 11))
    plt.yticks(np.arange(-0.5, 9.5),np.arange(1, 11))

这会给你这样的结果: