How do I draw a grid onto a plot in Python?

前端 未结 5 958
挽巷
挽巷 2020-12-04 06:06

I just finished writing code to make a plot using pylab in Python and now I would like to superimpose a grid of 10x10 onto the scatter plot. How do I do that?

My cur

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 06:45

    To show a grid line on every tick, add

    plt.grid(True)
    

    For example:

    import matplotlib.pyplot as plt
    
    points = [
        (0, 10),
        (10, 20),
        (20, 40),
        (60, 100),
    ]
    
    x = list(map(lambda x: x[0], points))
    y = list(map(lambda x: x[1], points))
    
    plt.scatter(x, y)
    plt.grid(True)
    
    plt.show()
    


    In addition, you might want to customize the styling (e.g. solid line instead of dashed line), add:

    plt.rc('grid', linestyle="-", color='black')
    

    For example:

    import matplotlib.pyplot as plt
    
    points = [
        (0, 10),
        (10, 20),
        (20, 40),
        (60, 100),
    ]
    
    x = list(map(lambda x: x[0], points))
    y = list(map(lambda x: x[1], points))
    
    plt.rc('grid', linestyle="-", color='black')
    plt.scatter(x, y)
    plt.grid(True)
    
    plt.show()
    

提交回复
热议问题