【问题标题】:Plotting multiple subplots want one colobar [duplicate]绘制多个子图需要一个 colobar [重复]
【发布时间】:2019-06-05 00:31:42
【问题描述】:

每个子图都有多个 colobar,我想要一个。

for i in range(6):
     plot.subplot(2,3,i)
     im=plot.contourf(xlon[:],xlat[:],rain[i,:,:])
     plot.colorbar(im)
plot.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以通过在其自己的轴上添加colorbar 来做到这一点。这可以通过手动创建一个附加轴并根据需要使用subplots_adjust()add_axes() 移动现有图来完成,例如

    import matplotlib.pyplot as plt
    import numpy as np
    import random
    
    fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
    for i in range(1,7):
        # This simply creates some random data to populate with
        a = np.arange(10)
        x, y = np.meshgrid(a, a)
        z = np.random.randint(0, 7, (10, 10))
    
        plt.subplot(2,3,i)
        im=plt.contourf(x, y, z)
    
    # Tight layout is optional
    fig.tight_layout()
    fig.subplots_adjust(right=0.825)
    cax = fig.add_axes([0.85, 0.06, 0.035, 0.91])
    fig.colorbar(im, cax=cax)
    plt.show()
    

    在这种情况下add_axes() 的参数是[left, bottom, width, height]。这将产生类似

    编辑

    要删除图间轴标签、刻度线等,需要对上述方法进行一些重要的修改,其中plt.subplots() 用于填充子图对象的2x3 数组,然后我们对其进行迭代。例如

    import matplotlib.pyplot as plt
    import numpy as np
    import random
    
    nrows = 2
    ncols = 3
    # Create the subplot array
    fig, (axes) = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 6), 
                               dpi=300, sharex=True, sharey=True)
    for i in range(nrows):
        for j in range(ncols):
            a = np.arange(10)
            x, y = np.meshgrid(a, a)
            z = np.random.randint(0, 7, (10, 10))
            im = axes[i][j].contourf(x, y, z)
            # Remove the tick marks but leave the superleft and superbottom alone
            if i != nrows-1:
                if j != 0:
                    axes[i][j].tick_params(axis='both', which='both', 
                               left=False, bottom=False, top=False)
                else:
                    axes[i][j].tick_params(axis='both', which='both', bottom=False, top=False)
            else:
                if j != 0:
                    axes[i][j].tick_params(axis='both', which='both', left=False, top=False)
    fig.tight_layout()
    # Some additional whitespace adjustment is needed
    fig.subplots_adjust(right=0.825, hspace=0.025, wspace=0.025)
    cax = fig.add_axes([0.85, 0.06, 0.035, 0.91])
    fig.colorbar(im, cax=cax)
    plt.show()
    

    【讨论】:

    • 感谢@William 成功了。
    • @MissPriyaKumari 如果正确回答问题,请务必点击答案旁边的复选标记
    • 谢谢下次我会注意到这一点。
    • 你能告诉我在上面的代码中我应该在哪里正确 sharex=True, sharey=True..我试图设置 x 和 y 轴值不显示在子图之间。
    • 上面的代码没问题,但是有一个更简单的方法:fig.colorbar(im, ax=axes) 会将颜色条放在ax 中列出的轴的右侧
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 2021-04-06
    • 1970-01-01
    • 2020-04-28
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多