Python画图|渐变背景

Python画图在有些时候,需要使用渐变过度。

在matplotlib官网中,提供了一个为柱状图画渐变背景的案例,我们一同探索一番。

【1】官网教程

点开下述链接,直达官网教程:

https://matplotlib.org/stable/gallery/lines_bars_and_markers/gradient_bar.html

官网教程代码本身带了很长的注释,但都是英文,此处我们自己尝试解读。

【2】代码注解

首先,引入画图模块matplotlib和计算模块numpy。

import matplotlib.pyplot as plt  # 引入matplotlib模块画图
import numpy as np  # 引入numpy模块做数学计算

然后,定义了随机数种子:

np.random.seed(19680801) #定义随机数种子

之后自定义了一个函数,这个函数很长,先记录如下:

def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs): #自定义函数
    """
    Draw a gradient image based on a colormap.

    Parameters
    ----------
    ax : Axes
        The Axes to draw on.
    direction : float
        The direction of the gradient. This is a number in
        range 0 (=vertical) to 1 (=horizontal).
    cmap_range : float, float
        The fraction (cmin, cmax) of the colormap that should be
        used for the gradient, where the complete colormap is (0, 1).
    **kwargs
        Other parameters are passed on to `.Axes.imshow()`.
        In particular, *cmap*, *extent*, and *transform* may be useful.
    """
    phi = direction * np.pi / 2 #定义因变量,从np.pi可以看出这是一个角度变量
    v = np.array([np.cos(phi), np.sin(phi)]) #定义数组,包括正弦值和余弦值
    X = np.array([[v @ [1, 0], v @ [1, 1]],
                  [v @ [0, 0], v @ [0, 1]]]) #这里的@是矩阵乘法运算符
    a, b = cmap_range #定义变量a和b
    X = a + (b - a) / X.max() * X #定义变量X
    im = ax.imshow(X, interpolation='bicubic', clim=(0, 1),
                   aspect='auto', **kwargs) #定义变量im
    return im #返回im

首先在第一行,

def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs): #自定义函数

这里引入了至少四个变量:

ax没有赋值,将从外部引入;

direction为一个常量,固定为0.3;

cmap_range是颜色取值代表,大小范围为(0,1);

之后定义了变量phi/v/X。

再后使用imshow()函数定义了im变量:

matplotlib.axes.Axes.imshow — Matplotlib 3.9.2 documentation

inshow()函数说明链接如上,主要负责将数字转换为图像。

之后定义了可画图函数:

def gradient_bar(ax, x, y, width=0.5, bottom=0): #自定义函数
    for left, top in zip(x, y):
        right = left + width #右边等于左边加宽度,这是要逐个排列的意思
        gradient_image(ax, extent=(left, right, bottom, top),
                       cmap=plt.cm.Blues_r, cmap_range=(0, 0.8))

gradient_bar()函数相对简单,其中的zip(x,y)是将x和y进行组合。

在该自动以函数中,直接调用了gradient_image()函数。

然后定义了要画图:

fig, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(0, 1))

再对gradient_image()函数进行了一次定义:

# background image
gradient_image(ax, direction=1, extent=(0, 1, 0, 1), transform=ax.transAxes,
               cmap=plt.cm.RdYlGn, cmap_range=(0.2, 0.8), alpha=0.5) #调用了子函数

最后输出图形:

N = 10 #定义常量10
x = np.arange(N) + 0.15 #使用随机变量参与运算制造变量x
y = np.random.rand(N) #定义随机矩阵
gradient_bar(ax, x, y, width=0.7) #画随机柱状图
plt.show() #输出图形

图像输出为:

图1

至此的完整代码为:

import matplotlib.pyplot as plt  # 引入matplotlib模块画图
import numpy as np  # 引入numpy模块做数学计算

np.random.seed(19680801) #定义随机数种子


def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs): #自定义函数
    """
    Draw a gradient image based on a colormap.

    Parameters
    ----------
    ax : Axes
        The Axes to draw on.
    direction : float
        The direction of the gradient. This is a number in
        range 0 (=vertical) to 1 (=horizontal).
    cmap_range : float, float
        The fraction (cmin, cmax) of the colormap that should be
        used for the gradient, where the complete colormap is (0, 1).
    **kwargs
        Other parameters are passed on to `.Axes.imshow()`.
        In particular, *cmap*, *extent*, and *transform* may be useful.
    """
    phi = direction * np.pi / 2 #定义因变量,从np.pi可以看出这是一个角度变量
    v = np.array([np.cos(phi), np.sin(phi)]) #定义数组,包括正弦值和余弦值
    X = np.array([[v @ [1, 0], v @ [1, 1]],
                  [v @ [0, 0], v @ [0, 1]]]) #这里的@是矩阵乘法
    a, b = cmap_range #定义变量a和b
    X = a + (b - a) / X.max() * X #定义变量X
    im = ax.imshow(X, interpolation='bicubic', clim=(0, 1),
                   aspect='auto', **kwargs) #定义变量im
    return im #返回im


def gradient_bar(ax, x, y, width=0.5, bottom=0): #自定义函数
    for left, top in zip(x, y):
        right = left + width #右边等于左边加宽度,这是要逐个排列的意思
        gradient_image(ax, extent=(left, right, bottom, top),
                       cmap=plt.cm.Blues_r, cmap_range=(0.2, 0.9))


fig, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(0, 1))

# background image
gradient_image(ax, direction=1, extent=(0, 1, 0, 1), transform=ax.transAxes,
               cmap=plt.cm.RdYlGn, cmap_range=(0.2, 0.9), alpha=0.5) #调用了子函数

N = 10 #定义常量10
x = np.arange(N) + 0.15 #使用随机变量参与运算制造变量x
y = np.random.rand(N) #定义随机矩阵
gradient_bar(ax, x, y, width=0.7) #画随机柱状图
plt.show() #输出图形

【3】代码修改

将gradient_bar()和gradient_image()里面的cmap_range都设置为(0.2, 0.9),也就是扩大渐变色程度。输出图像为:

图2

由图2可见,柱形图本身的渐变更为明显。

【4】总结

学习了官网的渐变柱状图和渐变背景画法,尝试修改了颜色渐变的程度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值