Minor ticks in matplotlib's colorbar

后端 未结 1 1014
无人共我
无人共我 2021-01-02 12:08

I\'m currently trying to set minor ticks in the colorbar but simply can\'t make it work. There are 3 approaches which I\'ve tried (see code below), but all of them didn\'t a

1条回答
  •  隐瞒了意图╮
    2021-01-02 12:33

    You're on the right track, you just need cb.ax.minorticks_on().

    For example:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import LogNorm
    
    # fill grid
    x = np.linspace(1,10,10)
    y = np.linspace(1,10,10)
    
    X, Y = np.meshgrid(x,y)
    Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)
    
    # plot
    f, ax = plt.subplots()
    p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
    cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)
    
    cb.ax.minorticks_on()
    
    plt.show()
    

    enter image description here


    If you want just the ticks that you specify, you still set them in the "normal" way, but be aware that the colorbar axes coordinate system ranges from 0-1 regardless of the range of your data.

    For that reason, to set the specific values that you want, we need to call the normalize the tick locations using the same norm instance that the image is using.

    For example:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import LogNorm
    
    # fill grid
    x = np.linspace(1,10,10)
    y = np.linspace(1,10,10)
    
    X, Y = np.meshgrid(x,y)
    Z = np.abs(np.cos(X**2 - Y**2) * X**2 * Y)
    
    # plot
    f, ax = plt.subplots()
    p = plt.pcolormesh(X, Y, Z, norm=LogNorm(), vmin=1e-2, vmax=1e2)
    cb = plt.colorbar(p, ax=ax, orientation='horizontal', aspect=10)
    
    # We need to nomalize the tick locations so that they're in the range from 0-1...
    minorticks = p.norm(np.arange(1, 10, 2))
    cb.ax.xaxis.set_ticks(minorticks, minor=True)
    
    plt.show()  
    

    enter image description here

    0 讨论(0)
提交回复
热议问题