Search code examples
python-3.xmatplotlibhistogramsubplotcolorbar

Adding one colorbar for hist2d subplots and make them adjacent


I am struggling with tweaking a plot, I have been working on. I am facing to two problems:

  1. The plots should be adjacent and with 0 wspace and hspace. I set both values to zero but still there are some spaces between the plots.
  2. I would like to have one colorbar for all the subplots (they all the same range). Right now, the code adds a colorbar to the last subplot as i understand that it needs the third return value of hist2D.

Here is my code so far:

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()

And the corrsiponding result:

Result

I would be glad for any heads up that i am missing!


Solution

  • You can use ImageGrid, which was designed to make this kind of things easier

    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')
    

    enter image description here

    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')
    

    enter image description here