# Checkerboard Graph

Learn how to use the meshgrid function to visualize three-dimensional data on a two-dimensional grid with colored squares.

We'll cover the following

Let’s learn how to illustrate a visualization technique in Matplotlib. Plotting a two-dimensional grid with colored squares or other shapes on it can be useful when you want to show three dimensions of data. Here, color illustrates the third dimension.

## Using NumPy’s meshgrid function to create a mesh grid

The first step in the process is to create grids of $x$ and $y$ coordinates. The NumPy meshgrid function can be used to do this. This function takes one-dimensional arrays of $x$ and $y$ coordinates and creates the mesh grid with all the possible pairs from both. The points in the mesh grid will be the corners of each square on the checkerboard plot. Here is how the code looks for a 4 x 4 grid of colored patches. Because we are specifying the corners, we require a 5 x 5 grid of points. We also show the arrays of the $x$ and $y$ coordinates:

xx_example, yy_example = np.meshgrid(range(5), range(5))
print(xx_example)
print(yy_example)


The output is as follows:

[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]
[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]


The grid of data to plot on this mesh should have a 4 x 4 shape. We make a one-dimensional array of integers between 1 and 16, and reshape it to a two-dimensional, 4 x 4 grid:

z_example = np.arange(1,17).reshape(4,4) z_example


This outputs the following:

array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])


## Creating the checkerboard graph

We can plot the z_example data on the xx_example, yy_example mesh grid with the following code. Notice that we use pcolormesh to make the plot with the jet colormap, which gives a rainbow color scale. We add a colorbar, which needs to be passed the pcolor_ex object returned by pcolormesh as an argument, so the interpretation of the color scale is clear:

ax = plt.axes()
pcolor_ex = ax.pcolormesh(xx_example, yy_example, z_example, cmap=plt.cm.jet)
plt.colorbar(pcolor_ex, label='Color scale')
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')


Get hands-on with 1200+ tech skills courses.