如何使用matplotlib创建某种类型的网格

时间:2014-04-25 16:56:58

标签: python matplotlib

我编写了一个解决n-queens问题的程序(在Python 3.3中),并以列表的形式给出了解决方案(例如[1,5,7,2,0,3,6,4])它指定了每行中女王的位置。例如,该特定列表长度为8个元素(因此它是n = 8的解决方案,或标准棋盘),我的程序将打印如下内容:

+---+---+---+---+---+---+---+---+
|   | ۩ |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   | ۩ |   |   |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   | ۩ |
+---+---+---+---+---+---+---+---+
|   |   | ۩ |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
| ۩ |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
|   |   |   | ۩ |   |   |   |   |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   | ۩ |   |
+---+---+---+---+---+---+---+---+
|   |   |   |   | ۩ |   |   |   |
+---+---+---+---+---+---+---+---+

我的问题是:我如何使用matplotlib做类似的事情,但没有ascii艺术?我想这样做是因为我使用的打印格式不允许大于96x96的电路板。

1 个答案:

答案 0 :(得分:3)

如果您使用的是带有女王符号的字体,那么您可能会这样做:

import matplotlib.pyplot as plt
import numpy as np

board = np.zeros((8,8,3))
board += 0.5 # "Black" color. Can also be a sequence of r,g,b with values 0-1.
board[::2, ::2] = 1 # "White" color
board[1::2, 1::2] = 1 # "White" color

positions = [1, 5, 7, 2, 0, 3, 6, 4]

fig, ax = plt.subplots()
ax.imshow(board, interpolation='nearest')

for y, x in enumerate(positions):
    # Use "family='font name'" to change the font
    ax.text(x, y, u'\u2655', size=30, ha='center', va='center')

ax.set(xticks=[], yticks=[])
ax.axis('image')

plt.show()

但是,我似乎无法在我的系统上找到一个带有该角色的字体,所以我得到:

enter image description here

您还可以使用图像作为符号:

import matplotlib.pyplot as plt
import numpy as np

board = np.zeros((8,8,3))
board += 0.5 # "Black" color
board[::2, ::2] = 1 # "White" color
board[1::2, 1::2] = 1 # "White" color

positions = [1, 5, 7, 2, 0, 3, 6, 4]

fig, ax = plt.subplots()
ax.imshow(board, interpolation='nearest')

queen = plt.imread('queen.png')
extent = np.array([-0.4, 0.4, -0.4, 0.4]) # (0.5 would be the full cell)
for y, x in enumerate(positions):
    ax.imshow(queen, extent=extent + [x, x, y, y])

ax.set(xticks=[], yticks=[])
ax.axis('image')

plt.show()

enter image description here