matplotlib colorbar 标题挂在图外

matplotlit colorbar title hangs outside figure

指定颜色栏图例位置同时确保图例标题在图中的最佳方法是什么?有时位置会在右上角,如此处所示;但在其他地块中它将是可变的,upper/lower left/right.

解决方案不用inset_axes()也没关系。

备选方案: 如果颜色条图例在子图的右侧,如果“我的图例”标题是垂直和左侧,刻度标签在右侧和水平(我不知道该怎么做那个)。

使用 Python 3.8.

## Second Plot
vals2 = ax2.scatter(df.x, df.y, edgecolors = 'none', c = df.z,
            norm = mcolors.LogNorm(), cmap=rainbow)
ax2.set_aspect('equal')
ax2.set_title('Subplot Title', style='italic');
ax2.set_xlabel('x');
ax2.set_ylabel('y');

cbaxes = inset_axes(ax2, width="30%", height="10%", location = 'upper right')
clb = plt.colorbar(vals2, cax=cbaxes, format = '%1.2f', orientation='horizontal');
clb.ax.set_title('My Legend')

我仍然希望将颜色条(带有刻度标签和标题)放在 子图中;但我确实找到了一种方法来执行 替代解决方案:

vals2 = ax2.scatter(df.x, df.y, edgecolors = 'none', c = df.z,
            norm = mcolors.LogNorm(), cmap=rainbow)
ax2.set_aspect('equal')
ax2.set_title('Subplot Title', style='italic');
ax2.set_xlabel('x');
ax2.set_ylabel('y');
clb = fig.colorbar(slips2, ax=ax2, format = '%1.2g', location='right', aspect=25)
clb.ax.set_ylabel('My Legend')
clb.ax.yaxis.set_label_position('left')

颜色条比子图高,因为根据另一个子图(ax1,未显示)中的限制,ax2 被限制为相等的 xy 纵横比。