Plotting Points on Matplotlib Colored Grid

Viewed 23

I am working with the matplotlib library to generate colored graphs which need to have specific points overlayed on top of them. After messing around with matplotlib, I came up with a method to properly color my grid, however I am unable to plot points manually.

def generate_grid(x, y, data):
    fig, ax = plt.subplots(1, 1, tight_layout=True)
    my_cmap = matplotlib.colors.ListedColormap(['grey'])
    my_cmap.set_bad(color='w', alpha=0)
    for x in range(x + 1):
        ax.axhline(x, lw=2, color='k', zorder=5)
    for y in range(y+1):
        ax.axvline(y, lw=2, color='k', zorder=5)

    ax.imshow(data, interpolation='none', cmap=my_cmap,
              extent=[0, y, 0, x], zorder=0)

    plt.locator_params(axis="x", nbins=x+1)
    plt.locator_params(axis="y", nbins=y+1)

    locs, labels = plt.xticks()
    labels = [int(item)+1 for item in locs]
    plt.xticks(locs, labels)

    locs, labels = plt.yticks()
    z = len(locs)
    labels = [z-int(item) for item in locs]
    plt.yticks(locs, labels)

    ax.xaxis.tick_top()
    plt.show()

Generated grid

How would I go about plotting a point at any given location ie at (4,2) or (2,1)?

1 Answers

You may simply use the scatter method from within your generate_grid function, for instance, immediately before plt.show().

However, note that if you simply use ax.scatter(2,1, s=50) the symbol will end up under your grid.

You need to play with the zorder parameter to ensure that it appears over the grid. For instance ax.scatter(2,1, s=50, zorder=50) did the trick for me:

enter image description here

Related