Chess Board Using MatPlotLib Python

In this article, we will learn how to create a chessboard using Python.

In this, for creating a chessboard we are going to use MatPlotLib and Numpy Python modules.

Create a Chess Board in Python

1. Firstly, import all the necessary modules (i.e. numpy, matplotlib.pyplot, matplotlib.colors).

2. Declare the size of the interval dx, dy.

3. Create an array x and y that store all values from range -4 to 4 (since we need square) with interval dx and dy respectively. arange() is a numpy inbuilt function that returns an array of objects that are evenly spaced values within a defined interval.

4. Use np.meshgrid function to plot a rectangle grid with vector coordinates.

5. For calculating the alternating position for coloring use the outer function which basically returns the product of two vectors and modulus the result by 2.

6. Finally, use imshow function in MatPlotLib which helps to plot. title() function used to set the title of the plot.

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.colors import LogNorm 
dx, dy = 0.015, 0.05 
x = np.arange(-4.0, 4.0, dx) 
y = np.arange(-4.0, 4.0, dy) 
X, Y = np.meshgrid(x,y) 
min_max = np.min(x), np.max(x), np.min(y), np.max(y) 
res = np.add.outer(range(8), range(8))%2 
plt.imshow(res, cmap="binary_r")
plt.xticks([])
plt.yticks([])
plt.title("Chess Board Using Matplotlib Python") 
plt.show()

Outputchess board using matplotlib in Python

Also, refer

Polar contour plot in Matplotlib in Python

Leave a Reply

Your email address will not be published. Required fields are marked *