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