Search code examples
pythonmatplotlibsubplot

Remove gaps between subplots_mosaic in matplotlib


How do I remove the gaps between the subplots on a mosaic? The traditional way does not work with mosaics:

plt.subplots_adjust(wspace=0, hspace=0)

I also tried using gridspec_kw, but no luck.

import matplotlib.pyplot as plt
import numpy as np

ax = plt.figure(layout="constrained").subplot_mosaic(
    """
    abcde
    fghiX
    jklXX
    mnXXX
    oXXXX
    """,
    empty_sentinel="X",
    gridspec_kw={
        "wspace": 0,
        "hspace": 0,
    },
)


for k,ax in ax.items():
    print(ax)
    #ax.text(0.5, 0.5, k, transform=ax.transAxes, ha="center", va="center", fontsize=8, color="darkgrey")
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(length = 0)

The code generates: enter image description here


Solution

  • This is not caused by subplot_mosaic but because a layout was specified. If you use constrained or tight layout, the layout manager will supersede the custom adjustments.

    Remove the layout manager and either method will work:

    • gridspec_kw

      fig = plt.figure() # without layout param
      ax = fig.subplot_mosaic(
          """
          abcde
          fghiX
          jklXX
          mnXXX
          oXXXX
          """,
          empty_sentinel="X",
          gridspec_kw={
              "wspace": 0,
              "hspace": 0,
          },
      )
      
    • subplots_adjust

      fig = plt.figure() # without layout param
      ax = fig.subplot_mosaic(
          """
          abcde
          fghiX
          jklXX
          mnXXX
          oXXXX
          """,
          empty_sentinel="X",
      )
      fig.subplots_adjust(wspace=0, hspace=0)