我有一个9 sibplots图(3行x 3列)。我想绘制图形的背景颜色(不是子情节!)每行都有不同的颜色。这是我到目前为止所拥有的:
# 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()
这个数字是错误的,因为它给每个子情节中的背景上色。但是我想要的是为每行不同地着色图形背景(子情节之外)。我该怎么做呢?
像这样的?
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()
matplotlib的代码__版本__
以下代码适用于旧版本的matplotlib,其中Figure.add_artist()
不存在。然而,我发现将矩形添加到其中一个轴会导致该轴背景补丁的问题,所以我不得不隐藏所有背景以获得一致的外观。
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()