matplotlib gridspec子图的彩色背景

0ejtzxu1  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(157)

我想为我的图的每个子图都有一个背景。在我的例子中,我想左边是红色,右边是蓝色。

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

我该如何编码这种行为?

vlurs2pr

vlurs2pr1#

您正在设置轴面颜色,而要更改地物面颜色。
如果你想要两种颜色,你可以创建subfigures而不是子图:

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

flvlnr44

flvlnr442#

您可以在人物的两侧添加一些matplotlib.patches.Rectangles来创建明显的背景:
(this代码确实假设子图的位置位于居中垂直分隔线的两侧)

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

相关问题