添加渐变背景

有时候,我们希望在绘图时添加渐变背景,这样可以使图像更加美观。我们可以使用fig.figimage方法来添加渐变背景。fig.figimage方法可以在figure上添加一个图像,参数cmap表示颜色映射,参数resize表示是否调整大小,参数origin表示图像的原点位置。我们可以使用LinearSegmentedColormap.from_list()方法来创建一个颜色映射。

注意:如果使用fig.figimage方法添加渐变背景,必须保证绘图dpi和保存dpi一致,否则会出现背景不一致的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from matplotlib.colors import LinearSegmentedColormap
fig = plt.figure(figsize=(cm(15), cm(10)),dpi=500)
ax = plt.gca()

# 创建自定义渐变色彩映射
# 斜向上,白色到蓝色渐变
colors = ["white", "#ffe2e2"] # 白色到蓝色
cmap = LinearSegmentedColormap.from_list("custom_gradient", colors, N=255)

# 为整个figure设置渐变背景
# 首先根据dpi算出gradient宽度和高度
gradient_width=int(fig.dpi*fig.get_figwidth())
gradient_height=int(fig.dpi*fig.get_figheight())
# 然后生成斜向上的渐变(左下到右上,白到蓝)
gradient = np.linspace(0, 1, gradient_width)
gradient = np.tile(gradient, (gradient_height, 1))
gradient = (gradient + np.linspace(0, 1, gradient_height)[:, None]) / 2

# 将渐变设置为figure的背景
fig.figimage(cmap(gradient), resize=False,origin="lower")
# 确保坐标轴显示在渐变之上
ax.set_zorder(10)
ax.patch.set_alpha(0) # 使坐标轴背景透明,以便看到渐变

之后就可以加入正常的绘图代码了,加入绘图代码后的绘图结果如下所示

plot1.webp