为 hist2d 子图添加一个颜色条并使它们相邻

2024-05-02

我正在努力调整情节,我一直在努力。 我面临两个问题:

  1. 这些图应该是相邻的并且 wspace 和 hspace 为 0。我将两个值都设置为零,但图之间仍然有一些空格。
  2. 我想为所有子图使用一个颜色条(它们的范围都相同)。现在,代码向最后一个子图添加了一个颜色条,因为我知道它需要 hist2D 的第三个返回值。

到目前为止,这是我的代码:

def plot_panel(pannel_plot):
fig, ax = plt.subplots(3, 2, figsize=(7, 7), gridspec_kw={'hspace': 0.0, 'wspace': 0.0}, sharex=True, sharey=True)
fig.subplots_adjust(wspace=0.0)
ax = ax.flatten()
xmin = 0
ymin = 0
xmax = 0.19
ymax = 0.19
hist2_num = 0
h =[]
for i, j in zip(pannel_plot['x'].values(), pannel_plot['y'].values()):
    h = ax[hist2_num].hist2d(i, j, bins=50, norm=LogNorm(vmin=1, vmax=5000), range=[[xmin, xmax], [ymin, ymax]])
    ax[hist2_num].set_aspect('equal', 'box')
    ax[hist2_num].tick_params(axis='both', top=False, bottom=True, left=True, right=False,
                              labelsize=10, direction='in')
    ax[hist2_num].set_xticks(np.arange(xmin, xmax, 0.07))
    ax[hist2_num].set_yticks(np.arange(ymin, ymax, 0.07))
    hist2_num += 1

fig.colorbar(h[3], orientation='vertical', fraction=.1)
plt.show()

以及相应的结果:

Result https://i.stack.imgur.com/ZDBVZ.png

如果我缺少任何提示,我会很高兴!


您可以使用图像网格 https://matplotlib.org/3.1.1/tutorials/toolkits/axes_grid.html?highlight=imagegrid,旨在使此类事情变得更容易

data = np.vstack([
    np.random.multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
    np.random.multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])


from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4, 6))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(3, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 cbar_mode="single",
                 cbar_location="right",
                 cbar_pad=0.1
                )
for ax in grid:
    h = ax.hist2d(data[:, 0], data[:, 1], bins=100)
fig.colorbar(h[3], cax=grid.cbar_axes[0], orientation='vertical')

or

data = np.vstack([
    np.random.multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
    np.random.multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])


from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4, 6))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(3, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 cbar_mode="single",
                 cbar_location="top",
                 cbar_pad=0.1
                )
for ax in grid:
    h = ax.hist2d(data[:, 0], data[:, 1], bins=100)
fig.colorbar(h[3], cax=grid.cbar_axes[0], orientation='horizontal')
grid.cbar_axes[0].xaxis.set_ticks_position('top')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 hist2d 子图添加一个颜色条并使它们相邻 的相关文章

随机推荐