添加渐变背景
有时候,我们希望在绘图时添加渐变背景,这样可以使图像更加美观。我们可以使用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)
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
fig.figimage(cmap(gradient), resize=False,origin="lower")
ax.set_zorder(10) ax.patch.set_alpha(0)
|
之后就可以加入正常的绘图代码了,加入绘图代码后的绘图结果如下所示
