2014-10-31 38 views
0

我正在做一個涉及滲流的任務 - 長話短說,我有一個數組代表一個網格,每個條目是-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

這可能是你的興趣http://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image – 2014-10-31 16:53:06

+1

可能能夠使用ANSI轉義序列和裝飾器顏色代碼塊的文本見:http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python – jmunsch 2014-10-31 20:02:40

回答

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

enter image description here

0

您還可以使用韓丁圖像在下面的圖片。代碼示例可在matplotlib gallerycookbook中獲得。

如果你想要,例如色彩尺度而不是尺寸比例,或者兩者兼而有之,從食譜中分解出兩種功能的人可能更容易適應。

您可以在這個topic中看到有關在Latex中製作這些圖的討論。 Hinton diagram from cookbook

相關問題