表示矩阵的“最简单”方法
我正在做一个关于渗透的作业——简单来说,我有一个数组的数组,表示一个网格,每个位置的值是 -1、0 或 1。我基本上完成了作业,但有一部分要求用颜色来图形化表示这个矩阵的每个可能的值。不过根据作业的描述,我感觉可能不应该使用 Python 2.7 和 numpy 以外的其他东西。
我想不出其他办法,所以我就直接导入了 pylab,并在散点图中把每个坐标绘制成一个大彩色方块。但我心里总觉得可能有更好的方法,比如说有更合适的库可以用,或者用 numpy 就能做到。有没有什么建议?
如果有帮助的话,我目前的代码在下面。
def show_perc(sites):
n = sites.shape[0]
# Blocked reps the blocked sites, etc., the 1st list holds x-coords, 2nd list holds y.
blocked = [[],[]]
full = [[],[]]
vacant = [[],[]]
# i,j are row,column, translate this to x,y coords. Rows tell up-down etc., so needs to
# be in 1st list, columns in 0th. Top row 0 needs y-coord value n, row n-1 needs coord 0.
# Column 0 needs x-coord 0, etc.
for i in range(n):
for j in range(n):
if sites[i][j] > 0.1:
vacant[0].append(j)
vacant[1].append(n-i)
elif sites[i][j] < -0.1:
full[0].append(j)
full[1].append(n-i)
else:
blocked[0].append(j)
blocked[1].append(n-i)
pl.scatter(blocked[0], blocked[1], c='black', s=30, marker='s')
pl.scatter(full[0], full[1], c='red', s=30, marker='s')
pl.scatter(vacant[0], vacant[1], c='white', s=30, marker='s')
pl.axis('equal')
pl.show()
2 个回答
1
如果你不能使用其他库,那你就只能用ASCII艺术来表示内容。比如:
>>> import numpy as np
>>> a = np.random.randint(-1, 2, (5,5))
>>> a
array([[ 0, 0, 1, 1, 0],
[ 1, -1, 0, -1, 0],
[-1, 0, 0, 1, -1],
[ 0, 0, -1, -1, 1],
[ 1, 0, 1, -1, 0]])
>>>
>>>
>>> b[a<0] = '.'
>>> b = np.empty(a.shape, dtype='S1')
>>> b[a<0] = '_'
>>> b[a==0] = ''
>>> b[a>0] = '#'
>>> b
array([['', '', '#', '#', ''],
['#', '_', '', '_', ''],
['_', '', '', '#', '_'],
['', '', '_', '_', '#'],
['#', '', '#', '_', '']],
dtype='|S1')
>>>
>>> for row in b:
... for elm in row:
... print elm,
... print
...
# #
# _ _
_ # _
_ _ #
# # _
>>>
但是,如果你可以使用matplotlib这个库,你就可以用 imshow
来绘制你的矩阵了:
>>> import matplotlib.pyplot as plt
>>> plt.ion()
>>> plt.imshow(a, cmap='gray', interpolation='none')