Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my grid offset in this example?

I am trying to draw a randomly occupied grid with matplotlib. The grid looks offset from the blocks by a random amount:

The grid

Here is the code:

import matplotlib.pyplot as plt
import numpy as np

# Make a 10x10 grid...
nrows, ncols = 10,10
# Fill the cells randomly with 0s and 1s
image = np.random.randint(2, size = (nrows, ncols))

# Make grid
vgrid = []
for i in range(nrows + 1):
    vgrid.append((i - 0.5, i - 0.5))
    vgrid.append((- 0.5, 9.5))

hgrid = []
for i in range(ncols + 1):
    hgrid.append((- 0.5, 9.5))
    hgrid.append((i - 0.5, i - 0.5))

row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'j']

plt.matshow(image, cmap='Greys')
for i in range(11):
    plt.plot(hgrid[2 * i], hgrid[2 * i + 1], 'k-')
    plt.plot(vgrid[2 * i], vgrid[2 * i + 1], 'k-')

plt.axis([-0.5, 9.5, -0.5, 9.5])
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels)

plt.show()

The problem seems to happen when I enforce a plot area; this line:

plt.axis([-0.5, 9.5, -0.5, 9.5])

Also, please feel free to suggest a better method. I am new to pyplot.

like image 824
cvb0rg Avatar asked Nov 23 '25 07:11

cvb0rg


1 Answers

You can use plt.grid() to plot the axes grid. Unfortunately it won't solve the issue. The misalignment of the grid is a known issue for imshow (a function that is called by matshow).

I suggest to play with the figure size and the linewidth of the grid, until you get something acceptable.

plt.figure(figsize=(5,5));

nrows, ncols = 10,10
image = np.random.randint(2, size = (nrows, ncols))
row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'j']
plt.matshow(image, cmap='Greys',fignum=1,interpolation="nearest")

#set x and y ticks and labels
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels);

#set minor axes in between the labels
ax=plt.gca()
ax.set_xticks([x-0.5 for x in range(1,ncols)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,nrows)],minor=True)
#plot grid on minor axes
plt.grid(which="minor",ls="-",lw=2)

enter image description here

like image 107
Mel Avatar answered Nov 24 '25 21:11

Mel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!