pythonmatplotlib

How to fill spaces between subplots with a color in Matplotlib?


With the following code :

nb_vars=4

fig, axs = plt.subplots(4,4,figsize=(8,8), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100)
for i_ax in axs:
    for ii_ax in i_ax:
        ii_ax.set_yticklabels([])
for i_ax in axs:
    for ii_ax in i_ax:
        ii_ax.set_xticklabels([])

The space between the subplots is white. How is it possible to colour them ? And with different colors ? See for example this figure : enter image description here


Solution

  • You could add patches in between the axes:

    from matplotlib import patches
    
    nb_vars=4
    
    # colors between two axes in a row
    r_colors = [['#CC0000', '#CC0000', '#CC0000'],
                ['#0293D8', '#0293D8', '#0293D8'],
                ['#FF8E00', '#FF8E00', '#FF8E00'],
                ['#ABB402', '#ABB402', '#ABB402'],
               ]
    
    # colors between two axes in a column
    c_colors = [['#CC0000', '#0293D8', '#FF8E00', '#ABB402'],
                ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'],
                ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'],
               ]
    
    fig, axs = plt.subplots(4, 4, figsize=(4, 4),
                            gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100)
    h, w = axs.shape
    
    for r, i_ax in enumerate(axs):
        for c, ii_ax in enumerate(i_ax):
            ii_ax.set_yticklabels([])
            ii_ax.set_xticklabels([])
            ii_ax.plot([-r, r], [-c, c]) # plot dummy line for demo
            bbox = ii_ax.get_position()
            if r+1 < h:
                ii_ax.add_patch(patches.Rectangle((bbox.x0, bbox.y0),
                                                  bbox.width, -0.2,
                                                  facecolor=c_colors[r][c],
                                                  zorder=-1, clip_on=False,
                                                  transform=fig.transFigure, figure=fig
                                                 ))
            if c+1 < w:
                ii_ax.add_patch(patches.Rectangle((bbox.x1, bbox.y0),
                                                  0.2, bbox.height,
                                                  facecolor=r_colors[r][c],
                                                  zorder=-1, clip_on=False,
                                                  transform=fig.transFigure, figure=fig
                                                 ))
    

    Output:

    enter image description here