Colored background for gridspec subplots

Question:

I wanted to have a background for each subplot of my figure.
In my example, I want the left side to be red and the right side to be blue.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1,2,figure=fig)

data1 = np.random.rand(10,10)
data2 = np.random.rand(10,10)

ax_left = fig.add_subplot(gs[:,0], facecolor='red')
ax_left.set_title('red')
img_left = ax_left.imshow(data1, aspect='equal')

ax_right = fig.add_subplot(gs[:,1], facecolor='blue')
ax_right.set_title('blue')
img_right = ax_right.imshow(data2, aspect='equal')

plt.show()

How can I code this behavior?

Asked By: Mo0nKizz

||

Answers:

You can add some matplotlib.patches.Rectangles to either side of your figure to create apparent backgrounds:

(this code does make the assumption about the positions of your subplots being on either side of a centered vertical divider)

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1,2,figure=fig)

data1 = np.random.rand(10,10)
data2 = np.random.rand(10,10)

ax_left = fig.add_subplot(gs[:,0], facecolor='red')
ax_left.set_title('red')
img_left = ax_left.imshow(data1, aspect='equal')

ax_right = fig.add_subplot(gs[:,1], facecolor='blue')
ax_right.set_title('blue')
img_right = ax_right.imshow(data2, aspect='equal')

# Add rectangles here, zorder is important to insert the rectangles
#   underneath your plots instead of on top of them.
from matplotlib.patches import Rectangle
fig.add_artist(Rectangle((0, 0), width=.5, height=1, facecolor='red', zorder=0))
fig.add_artist(Rectangle((0.5, .0), width=.5, height=1, facecolor='blue', zorder=0))

plt.show()

enter image description here

Answered By: Cameron Riddell

You are setting the axes facecolors, while you want to change the figure facecolor.

If you want two colors, you can create subfigures instead of subplots:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

data1 = np.random.rand(10, 10)
data2 = np.random.rand(10, 10)

fig = plt.figure(figsize=(8, 4))
gs = fig.add_gridspec(1, 2)

fig_left = fig.add_subfigure(gs[:, 0])
fig_right = fig.add_subfigure(gs[:, 1])

fig_left.set_facecolor("red")
ax_left = fig_left.subplots()
ax_left.set_title("red")
img_left = ax_left.imshow(data1, aspect="equal")

fig_right.set_facecolor("blue")
ax_right = fig_right.subplots()
ax_right.set_title("blue")
img_right = ax_right.imshow(data2, aspect="equal")

plt.show()

colored backgrounds red and blue

Answered By: paime
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.