How to Create a Grid Anchored to the Bottom Left Corner?

Viewed 81

I'm trying to create a grid using matplotlib where the origin is at the bottom left corner. However, the origin is offset from the corner a little, which results in misalignment of the filled in tiles and the gridlines. Is there a parameter that I should be setting to align the graph? I tried adding plt.margins(x=0,y=0), but the graph doesn't change.

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

def plot_binary_map(stateMatrix):
    plt.margins(x=0,y=0)
    fig, ax = plt.subplots()
    spacing = 1.0
    loc = MultipleLocator(spacing)
    loc2 = MultipleLocator(spacing)
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc2)
    plt.grid(b=True)
    plt.imshow(stateMatrix, cmap='Greys')
    plt.savefig('stateValueMatrix.png')
    plt.show()

This is what I get when I run the code. You can see the filled in tiles (black) are not constrianed to the grid cells. enter image description here I would like my graph to look like this: enter image description here

1 Answers

I found this answer on SO, and the set_xticks method seems to have fixed the alignment issues.

def plot_grid(data, saveImageName, rows, cols):
    fig, ax = plt.subplots()
    ax.imshow(data, cmap=cmap)
    # draw gridlines
    ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=1)
    ax.set_xticks(np.arange(.5, rows, 1));
    ax.set_yticks(np.arange(.5, cols, 1));
    plt.tick_params(axis='both', labelsize=0, length = 0)
    plt.savefig(saveImageName + ".png", dpi=500)
Related