【问题标题】:Set the number of minor ticks in matplotlib colorbar在 matplotlib 颜色栏中设置次要刻度的数量
【发布时间】:2022-01-20 22:03:55
【问题描述】:

我可以使用从here借来的以下代码来设置颜色条的主要刻度数:

cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)

有没有类似的方法来设置颜色条的小刻度?

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:

    您可以使用AutoMinorLocator 设置次要刻度的数量(注意,在设置n=4 时,主要刻度之一被计为1)。这是一个例子:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import AutoMinorLocator, ScalarFormatter
    import numpy as np
    
    data = np.random.rand(10, 10)
    
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
    
    img1 = ax1.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
    cbar1 = plt.colorbar(img1, ax=ax1)
    ax1.set_title('default colorbar ticks')
    
    img2 = ax2.imshow(data, cmap='inferno', aspect='auto', vmin=0, vmax=1)
    cbar2 = plt.colorbar(img2, ax=ax2)
    # 3 major ticks
    cbar2.ax.locator_params(nbins=3)
    # 4 minor ticks, including one major, so 3 minor ticks visible
    cbar2.ax.yaxis.set_minor_locator(AutoMinorLocator(n=4))
    # show minor tick labels
    cbar2.ax.yaxis.set_minor_formatter(ScalarFormatter())
    # change the color to better distinguish them
    cbar2.ax.tick_params(which='minor', color='blue', labelcolor='crimson')
    ax2.set_title('3 major, 4 minor colorbar ticks')
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2013-02-21
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多