Matplotlib子图的彩色背景

hsgswve4  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(178)

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

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

我该如何对这种行为进行编码?先谢谢你。

1hdlvixo

1hdlvixo1#

您正在设置轴的面颜色,同时希望更改体形的面颜色。
如果需要两种颜色,可以创建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()

dgiusagp

dgiusagp2#

您可以在图形的任意一侧添加一些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()

相关问题