Change grid interval and specify tick labels in Matplotlib

前端 未结 2 1528
花落未央
花落未央 2020-12-02 04:22

I am trying to plot counts in gridded plots, but I am not being able to figure out how I go about it. I want to:

  1. Have dotted grids at an interval of 5

2条回答
  •  攒了一身酷
    2020-12-02 04:41

    A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

    import matplotlib.pyplot as plt
    from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
    
    fig, ax = plt.subplots(figsize=(10, 8))
    
    # Set axis ranges; by default this will put major ticks every 25.
    ax.set_xlim(0, 200)
    ax.set_ylim(0, 200)
    
    # Change major ticks to show every 20.
    ax.xaxis.set_major_locator(MultipleLocator(20))
    ax.yaxis.set_major_locator(MultipleLocator(20))
    
    # Change minor ticks to show every 5. (20/4 = 5)
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    
    # Turn grid on for both major and minor ticks and style minor slightly
    # differently.
    ax.grid(which='major', color='#CCCCCC', linestyle='--')
    ax.grid(which='minor', color='#CCCCCC', linestyle=':')
    

提交回复
热议问题