【问题标题】:2 subplots sharing y-axis (no space between) with single color bar2 个子图与单色条共享 y 轴(之间没有空格)
【发布时间】:2014-09-07 17:12:17
【问题描述】:

有没有人有两个图共享 y 轴(图之间没有空格)的 matplotlib 示例,其中一个颜色条与两个子图有关?我还没有找到这方面的例子。

【问题讨论】:

    标签: python python-2.7 matplotlib subplot colorbar


    【解决方案1】:

    我根据您的问题创建了以下代码。就我个人而言,我不喜欢在子图之间没有空间。如果您确实想在某个时候更改此设置,只需将 plt.subplots_adjust(wspace = -.059) 替换为 plt.tight_layout()

    希望对你有帮助

    import numpy
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    #Random data
    data = numpy.random.random((10, 10))
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(1,2,1, aspect = "equal")
    ax2 = fig.add_subplot(1,2,2, aspect = "equal", sharey = ax1)  #Share y-axes with subplot 1
    
    #Set y-ticks of subplot 2 invisible
    plt.setp(ax2.get_yticklabels(), visible=False)
    
    #Plot data
    im1 = ax1.pcolormesh(data)
    im2 = ax2.pcolormesh(data)
    
    #Define locations of colorbars for both subplot 1 and 2
    divider1 = make_axes_locatable(ax1)
    cax1 = divider1.append_axes("right", size="5%", pad=0.05)
    
    divider2 = make_axes_locatable(ax2)
    cax2 = divider2.append_axes("right", size="5%", pad=0.05)
    
    #Create and remove the colorbar for the first subplot
    cbar1 = fig.colorbar(im1, cax = cax1)
    fig.delaxes(fig.axes[2])
    
    #Create second colorbar
    cbar2 = fig.colorbar(im2, cax = cax2)
    
    #Adjust the widths between the subplots
    plt.subplots_adjust(wspace = -.059)
    
    plt.show()
    

    结果如下:

    【讨论】:

    • 如果fig = plt.figure() ax1 = fig.add_subplot(1,2,1, aspect = "equal") ax2 = fig.add_subplot(1,2,2, aspect = "equal", sharey = ax1) 的结果是AttributeError: 'Text' object has no attribute '_adjustable' 怎么办?
    • @durbachit,如果我复制粘贴您提供的行,我将无法重现您的错误。我猜你的错误有不同的起源。我建议您尝试运行您在评论中发布的三行代码。如果您能够使用这三行产生错误,我建议您查看 matplotlib 的版本。我使用的是:1.5.1.
    猜你喜欢
    • 2014-05-01
    • 2019-05-01
    • 2021-05-12
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多