【问题标题】:Align matplotlib subplot axes with and without colorbars (for more than 2 axes)使用和不使用颜色条对齐 matplotlib 子图轴(超过 2 个轴)
【发布时间】:2019-08-05 15:12:24
【问题描述】:

当有些子图有颜色条而其他子图没有时,如何对齐不同子图的轴?

import numpy as np
import matplotlib.pyplot as plt

data1 = np.random.random([15,15])
data2 = np.random.random(15)

fig, [[ax1, ax2], [ax3, ax4], [ax5, ax6]] = plt.subplots(3,2)

for ax in [ax1, ax2, ax4, ax5, ax6]:
    plt.sca(ax)
    plt.pcolormesh(data1)
    plt.colorbar()

plt.sca(ax3)
plt.plot(data2)

我想在ax3 的左侧添加空格,以便与其他数字对齐。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

这是 constrained_layout 旨在做的事情:https://matplotlib.org/tutorials/intermediate/constrainedlayout_guide.html

fig, [[ax1, ax2], [ax3, ax4], [ax5, ax6]] = plt.subplots(3,2,
        constrained_layout=True)

【讨论】:

    【解决方案2】:

    这是迄今为止最好的方法(基于https://stackoverflow.com/a/54473867/2383070)。

    我仍然想知道是否有更简单的方法,例如在轴的左侧添加空格。

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import numpy as np
    
    data1 = np.random.random([15,15])
    data2 = np.random.random(15)
    
    
    fig, [[ax1, ax2], [ax3, ax4], [ax5, ax6]] = plt.subplots(3,2)
    
    for ax in [ax1, ax2, ax4, ax5, ax6]:
        im1 = ax.pcolormesh(data1, cmap='magma')
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=.05)
        plt.colorbar(im1, cax=cax)
    
    im2 = ax3.plot(data2)
    divider2 = make_axes_locatable(ax3)
    cax2 = divider2.append_axes("right", size="5%", pad=.05)
    cax2.remove()
    

    【讨论】:

    • 我猜“只需在轴的左侧添加空格”将转化为使用您链接到的帖子之一中的this answer。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2018-08-04
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多