I am doing an assignment involving percolation–long story short, I have an array of arrays that represents a grid, and every entry is -1, 0, or 1. I have the assignment essentially done, but one part asks for a graphical representation of the matrix using colors for each possible entry. But from the way the assignment is worded, it sounds to me like perhaps I shouldn’t be using anything not found in standard Python 2.7 and numpy.

I couldn’t think of how to do it so I just went ahead and import pylab and plotted every coordinate as a large colored square in a scatter plot. But I just have this nagging concern that there’s a better way to do it–like there’s a better package to use for this task, or like there’s a way to do it with just numpy. Suggestions?

If it helps, my current code is below.

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

## Answer

If you’re not allowed to use other libraries, you’re stuck with ASCII art. For example:

>>> 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 ... # # # _ _ _ # _ _ _ # # # _ >>>

But, if you can use matplotlib, you can just use `imshow`

to plot your matrix:

>>> import matplotlib.pyplot as plt >>> plt.ion() >>> plt.imshow(a, cmap='gray', interpolation='none')