Matplotlib情节numpy的矩阵作为0索引

我制备numpy的矩阵,然后使用matplotlib绘制矩阵,如:Matplotlib情节numpy的矩阵作为0索引

>>> import numpy 

>>> import matplotlib.pylab as plt

>>> m = [[0.0, 1.47, 2.43, 3.44, 1.08, 2.83, 1.08, 2.13, 2.11, 3.7], [1.47, 0.0, 1.5, 2.39, 2.11, 2.4, 2.11, 1.1, 1.1, 3.21], [2.43, 1.5, 0.0, 1.22, 2.69, 1.33, 3.39, 2.15, 2.12, 1.87], [3.44, 2.39, 1.22, 0.0, 3.45, 2.22, 4.34, 2.54, 3.04, 2.28], [1.08, 2.11, 2.69, 3.45, 0.0, 3.13, 1.76, 2.46, 3.02, 3.85], [2.83, 2.4, 1.33, 2.22, 3.13, 0.0, 3.83, 3.32, 2.73, 0.95], [1.08, 2.11, 3.39, 4.34, 1.76, 3.83, 0.0, 2.47, 2.44, 4.74], [2.13, 1.1, 2.15, 2.54, 2.46, 3.32, 2.47, 0.0, 1.78, 4.01], [2.11, 1.1, 2.12, 3.04, 3.02, 2.73, 2.44, 1.78, 0.0, 3.57], [3.7, 3.21, 1.87, 2.28, 3.85, 0.95, 4.74, 4.01, 3.57, 0.0]]

>>> matrix = numpy.matrix(m)

>>> matrix

matrix([

[ 0. , 1.47, 2.43, 3.44, 1.08, 2.83, 1.08, 2.13, 2.11, 3.7 ],

[ 1.47, 0. , 1.5 , 2.39, 2.11, 2.4 , 2.11, 1.1 , 1.1 , 3.21],

[ 2.43, 1.5 , 0. , 1.22, 2.69, 1.33, 3.39, 2.15, 2.12, 1.87],

[ 3.44, 2.39, 1.22, 0. , 3.45, 2.22, 4.34, 2.54, 3.04, 2.28],

[ 1.08, 2.11, 2.69, 3.45, 0. , 3.13, 1.76, 2.46, 3.02, 3.85],

[ 2.83, 2.4 , 1.33, 2.22, 3.13, 0. , 3.83, 3.32, 2.73, 0.95],

[ 1.08, 2.11, 3.39, 4.34, 1.76, 3.83, 0. , 2.47, 2.44, 4.74],

[ 2.13, 1.1 , 2.15, 2.54, 2.46, 3.32, 2.47, 0. , 1.78, 4.01],

[ 2.11, 1.1 , 2.12, 3.04, 3.02, 2.73, 2.44, 1.78, 0. , 3.57],

[ 3.7 , 3.21, 1.87, 2.28, 3.85, 0.95, 4.74, 4.01, 3.57, 0. ]

])

>>> fig = plt.figure()

>>> ax = fig.add_subplot(1,1,1)

>>> ax.set_aspect('equal')

>>> plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean)

>>> plt.colorbar()

>>> plt.show()

该图示出这样的:

这是罚款,除了我希望我的轴从1-10,而不是0-9(衍生自python的0索引)的事实

有没有简单的方法来做到这一点?

非常感谢!

回答:

可以使用extent可选参数的plt.imshow()功能,这是记录here。就像这样:

#All the stuff earlier in the program 

plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean, extent=(0.5,10.5,0.5,10.5))

plt.colorbar()

plt.show()

对于任意形状的矩阵,可以将这个代码更改为类似这样:

#All the stuff earlier in the program 

plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean,

extent=(0.5,numpy.shape(matrix)[0]+0.5,0.5,numpy.shape(matrix)[1]+0.5))

plt.colorbar()

plt.show()

这将产生一个情节,看起来像这样:

回答:

以获得所需的输出代码之后添加这些行,但以前plt.show()

... 

labels = [0, 1, 3, 5, 7, 9]

ax.set_xticklabels(labels)

plt.show()

注意,X轴和Y轴的范围是[-0.5, 9.5]不是int [0, 9]

编辑:

要以更灵活的方式(事实上,上面显示的另一种方式):

labels = range(0, len(m[0])) 

plt.xticks(labels)

plt.show()

输出:

以上是 Matplotlib情节numpy的矩阵作为0索引 的全部内容, 来源链接: utcz.com/qa/264229.html

回到顶部