Matplotlib colorbar 扭曲了同一图中的另一个子图

问题描述 投票:0回答:1

在下面的代码中,变量

mat_store
显示在中心轴上,然后折叠的条形图(横跨矩阵的每个轴)显示在矩阵的顶部和侧面。我还想在图的底部显示矩阵的颜色条。

        num_bins = mat_store.shape[0]
        fig = plt.figure(figsize=(16, 16))
        gs = fig.add_gridspec(3, 2,  width_ratios=(7, 2), height_ratios=(2, 7, 0.5),
                        left=0.1, right=0.9, bottom=0.1, top=0.9,
                        wspace=0.05, hspace=0.15)

        ax = fig.add_subplot(gs[1, 0])
        ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
        ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
        ax_histx.tick_params(axis="x", labelbottom=False)
        ax_histy.tick_params(axis="y", labelleft=False)
        
        abs_serial = jnp.abs(mat_store)
        cur_trial_dependence = jnp.sum(abs_serial,axis=0)
        pre_trial_dependence = jnp.sum(abs_serial,axis=1)
        ax_histx.bar(np.arange(num_bins)-0.5, cur_trial_dependence, align="edge",color='k',linewidth=0,width = 1)
        ax_histy.barh(np.arange(num_bins)-0.5, pre_trial_dependence, height = 1, align="edge",color='k',linewidth=0,alpha=0.25)
        ax_histy.get_xaxis().set_ticks([])
        ax_histx.get_yaxis().set_ticks([])
        ax_histx.tick_params(
            which='both',      # both major and minor ticks are affected
            bottom=False,      # ticks along the bottom edge are off
            top=False,         # ticks along the top edge are off
            labelbottom=False) # labels along the bottom edge are off
        ax_histy.tick_params(
            which='both',      # both major and minor ticks are affected
            left=False,
            right=False,
            labelbottom=False) # labels along the bottom edge are off
        max_value = jnp.max(abs_serial)
        hist = ax.imshow(mat_store,origin="lower",cmap="seismic",vmin=-max_value,vmax=max_value)
        ax.set_ylabel(r"$S_{n-1}$")
        ax.set_xlabel(r"$S_{n}$")
        ax.set_title(r"$\langle \{S_{n-1},S_{n}\} \rangle - \langle S_{n} \rangle$")
        
        ax.set_yticks([0,num_bins-1])
        ax.set_yticklabels([r"$-\pi$",r"$\pi$"])
        ax.set_xticks([0,num_bins-1])
        ax.set_xticklabels([r"$-\pi$",r"$\pi$"])
        ax.plot([0,num_bins-1],[0,num_bins-1],color="white",ls="--",lw=2)
        ax.axvline((num_bins-1)/2,color="white",ls="--",lw=2)
        ax.axhline((num_bins-1)/2,color="white",ls="--",lw=2)
        col_ax = fig.add_subplot(gs[2, 0])
        fig.colorbar(hist,cax = col_ax,orientation="horizontal")

产生这个图像

如您所见,存在几个问题。

  1. 我想向下移动颜色条,这样它就不会遮挡轴标签,也不会向上移动顶部的条形图,所以简单地修改
    hspace
    中的
    add_gridspec
    参数在这里是不合适的。移动轴标签(也垂直,为了保持一致性)也可以,但我也不知道该怎么做。
  2. 更大的问题,我很困惑,为什么在 gridspec 中添加 axtra 轴会使中心轴收缩?如果我没有第三行,矩阵将与顶行的条形图完美对齐。为什么添加第三行会改变中心轴的宽度?为什么它不修改第一行?我怎样才能解决这个问题,使所有子图的边缘对齐?
python matplotlib colorbar
1个回答
0
投票

您可以像

pad
一样使用
fig.colorbar(hist,cax = col_ax,orientation="horizontal", pad=0.2)
参数。这会修改颜色条的位置。

© www.soinside.com 2019 - 2024. All rights reserved.