【问题标题】:How to keep nested axes position while using subplots_adjust如何在使用 subplots_adjust 时保持嵌套轴的位置
【发布时间】:2021-11-09 10:23:04
【问题描述】:

我使用以下代码在每个子图的左上角添加一个颜色条。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

# Create figure
fig = plt.figure(figsize=(5, 2))

# Specify geometry of the grid for subplots
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)

# Data
a = np.arange(3*5).reshape(3,5)

for ax_i in range(3):
    # Create axes
    ax = plt.subplot(gs0[ax_i])

    # Plot data
    plot_pcolor = plt.pcolormesh(a)

    # ******** Plot a nested colorbar inside the plot ********
    # Define position of the desired colorbar in axes coordinate 
    # [(lower left x, lower left y), (upper right x, upper right y)]
    ax_coord = [(0.05, 0.5), (0.2, 0.95)]

    # Transform the two points from axes coordinates to display coordinates
    tr1 = ax.transAxes.transform(ax_coord)

    # Create an inverse transversion from display to figure coordinates
    inv = fig.transFigure.inverted()
    tr2 = inv.transform(tr1)

    # Position in figure coordinates [left, bottom, width, height]
    datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0], tr2[1,1]-tr2[0,1]]

    # Create colorbar axes
    cbar_ax = fig.add_axes(datco)

    # Plot colorbar
    cbar = plt.colorbar(plot_pcolor, cax=cbar_ax)
    # ********************************************************

if False:
    plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)

plt.savefig('test.png', dpi=500)

它给出了以下情节:

但是,如果我使用 subplots_adjust() 函数(通过将上面代码中的 False 替换为 True),颜色条将无法正常移动:

你知道我该如何处理吗?

【问题讨论】:

    标签: python matplotlib subplot colorbar axes


    【解决方案1】:

    使用mpl_toolkits 模块中的inset_axes() 函数可以解决问题。也可以简单地使用ax.inset_axes()

    这是新代码:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    
    # Create figure
    fig = plt.figure(figsize=(5, 2))
    
    # Specify geometry of the grid for subplots
    gs0 = gridspec.GridSpec(1, 3, wspace=0.7)
    
    # Data
    a = np.arange(3*5).reshape(3,5)
    
    for ax_i in range(3):
        # Create axes
        ax = plt.subplot(gs0[ax_i])
    
        # Plot data
        plot_pcolor = plt.pcolormesh(a)
    
        axins = inset_axes(ax, width="5%", height="50%", loc='upper left')
    
        # Plot colorbar
        cbar = plt.colorbar(plot_pcolor, cax=axins)
        # ********************************************************
    
    if True:
        plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)
    
    plt.savefig('test.png', dpi=500)
    

    结果如下:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多