Search code examples
python-3.xmatplotlibfigure

Python: Plot Different Figure Background Color For Each Row of Subplots


I have a figure of 9 sibplots (3 rows x 3 columns). I would like to plot the background color of the figure (not the subplots!) in a different color for each row. This is what I have so far:

# Imports
import matplotlib.pyplot as plt
import numpy as np

# Plot the Figure

fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(9, 9))

for r in np.arange(3):
    for c in np.arange(3):
        axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))
        if r == 0:
            axes[r, c].patch.set_facecolor('azure')
        if r == 1:
            axes[r, c].patch.set_facecolor('hotpink')
        if r == 2:
            axes[r, c].patch.set_facecolor('lightyellow')
plt.show()

This figure is wrong in the sense that it colors the background inside each subplot. But what I want is to color the figure background (outside the subplots) differently for each row. How can I do this?


Solution

  • something like this?

    fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(9, 9))
    
    for r in np.arange(3):
        for c in np.arange(3):
            axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))
    
    colors = ['azure','hotpink','lightyellow']
    for ax,color in zip(axes[:,0],colors):
        bbox = ax.get_position()
        rect = matplotlib.patches.Rectangle((0,bbox.y0),1,bbox.height, color=color, zorder=-1)
        fig.add_artist(rect)
    plt.show()
    

    enter image description here

    Code for matplotlib.__version__<3.0

    The following code works in older version of matplotlib where Figure.add_artist() does not exist. However, I found that adding the rectangle to one of the axes causes problem for that axes background patch, so I had to hide all the backgrounds for a consistent look.

    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    import numpy as np
    
    fig, axes = plt.subplots(nrows=3, ncols=3)
    
    for r in np.arange(3):
        for c in np.arange(3):
            axes[r, c].plot(np.arange(10), np.random.randint(10, size=10))
    
    fig.tight_layout()
    
    colors = ['azure','hotpink','lightyellow']
    for ax,color in zip(axes[:,0],colors):
        bbox = ax.get_position()
        rect = Rectangle((0,bbox.y0),1,bbox.height, color=color, zorder=-1, transform=fig.transFigure, clip_on=False)
        ax.add_artist(rect)
    for ax in axes.flat:
        ax.patch.set_visible(False)
    plt.show()
    

    enter image description here