Search code examples
pythonmatplotlibn-queens

How to insert a UTF-8 character onto an image


I created a chessboard with Python using Matplotlib and I want to know if it's possible to add an image in the squares I want.

I'm trying to replicate the 8-queens problem but with variable size, but my main problem is that I'm not sure how to show the queen in each square of the chessboard.

chessboard = np.zeros((size,size))

chessboard[1::2,0::2] = 1
chessboard[0::2,1::2] = 1

print(chessboard)
plt.imshow(chessboard,cmap='binary')
plt.show()

My plan is to create another np.zeros() with the same size but this time I will represent my queens.


Solution

  • You could plot a centered "text" with a UTF-8 queen character. You need to change the text color when printing on a black background.

    import matplotlib.pyplot as plt
    import numpy as np
    
    size = 8
    chessboard = np.zeros((size,size))
    
    chessboard[1::2,0::2] = 1
    chessboard[0::2,1::2] = 1
    
    plt.imshow(chessboard, cmap='binary')
    
    for _ in range(20):
        i, j = np.random.randint(0, 8, 2)
        plt.text(i, j, '♕', fontsize=20, ha='center', va='center', color='black' if (i - j) % 2 == 0 else 'white')
    
    plt.show()
    

    resulting plot