user3573835
user3573835

Reputation: 11

How to create a certain type of grid with matplotlib

I wrote a program (in Python 3.3) that solves the n-queens problem, and gives a solution in the form of a list (e.g. [1, 5, 7, 2, 0, 3, 6, 4]) which specifies the location of the queen in each row. For example, that particular list is 8 elements long (so it is a solution for n=8, or a standard chessboard) and my program would print something like this:

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

My question is: How would I use matplotlib to do something similar, but without the ascii art? I want to do this because the printing format I'm using doesn't allow for boards larger than 96x96.

Upvotes: 1

Views: 1119

Answers (1)

Joe Kington
Joe Kington

Reputation: 284980

If you're using a font that has the queen symbol, then you might do something like this:

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

However, I can't seem to find a font on my system that with that character, so I just get:

enter image description here

You could also use an image as the symbol:

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

Upvotes: 3

Related Questions