Search code examples
pythonmatplotlibplot

Set grid frequency for plot


I have a very simple code that plots points by coordinates (x, y)

def separate_file(coordinates):
    new_document_x, new_document_y = zip(*coordinates)
    plt.gca().invert_yaxis()
    plt.plot(new_document_x, new_document_y, "r", marker='.', linestyle='None')
    plt.show()

print(separate_file(
[[184, 60], [33, 76], [33, 128], [33, 180], [327, 149], [33, 325], [399, 598], [221, 625]]
))

output enter image description here

But I would like to add a grid to this graph. On the x-axis with a frequency of 100, and on the y-axis with a frequency of 200.

enter image description here

I tried some options from the internet but didn't get the desired result. Please tell me how can I achieve this


Solution

  • You could play with the Axis ticks to make your custom grid (same logic described here) :

    import matplotlib.pyplot as plt
    
    def separate_file(coo, xoff=100, yoff=200):
        def mloc(axis, mul):
            axis.set_major_locator(plt.MultipleLocator(mul))
            axis.set_minor_locator(plt.MultipleLocator(mul/2))
            axis.set_minor_formatter(plt.ScalarFormatter())
            
        ax = plt.gca()
        ax.invert_yaxis()
        ax.scatter(*zip(*coo), c="blue", s=10, zorder=2)
    
        # grid
        mloc(ax.xaxis, xoff)
        mloc(ax.yaxis, yoff)
        ax.tick_params(which="both", length=3)
        ax.grid(which="major", c="orange", lw=1.5)
    
        plt.show()
    

    enter image description here