matplotlib提供了两个比较方便的填充折线图的方式:
- matplotlib.pyplot.fill_between:
竖直方向填充
matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, \*, data=None, \*\*kwargs)
- paremeters:
- x: array (length N)
The x coordinates of the nodes defining the curves.
array数组,定义曲线节点的x的坐标值。 - y1: array (length N) or scalar
The y coordinates of the nodes defining the first curve.
array数组或者标量,第一条曲线的y的节点的坐标值。 - y2: array (length N) or scalar, optional, default: 0
The y coordinates of the nodes defining the second curve.
array数组或者标量,可选,默认为0,第二条曲线的节点的坐标值。
- x: array (length N)
- matplotlib.pyplot.fill_betweenx
水平方向填充
matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, \*, data=None, \*\*kwargs)
- parameters:
- y: array (length N)
The y coordinates of the nodes defining the curves.
array数组,定义曲线的节点对应的y的坐标。 - x1: array (length N) or scalar
The x coordinates of the nodes defining the first curve.
array数组或者标量,定义第一条曲线的节点对应的x的坐标 - x2: array (length N) or scalar, optional, default: 0
The x coordinates of the nodes defining the second curve.
array数组或者标量,定义第二条曲线的节点对应的x的坐标
- y: array (length N)
import numpy as np
import matplotlib.pyplot as plt
# 设置numpy的随机种子,保证每次随机得到的值一致
np.random.seed(233)
# 定义一个10个长度的,每个元素为0的array
zero_array = np.zeros(shape=[10, ])
# 使用5对上面的数组进行填充
zero_array.fill(5)
# 生成10随机数的数组,最大值为3,最小值为-3
random_num = np.random.randint(low=-3, high=3, size=10)
fill_array = zero_array + random_num
print(fill_array)
# 设置画布个数和尺寸
fig = plt.figure(num=3, figsize=[16, 4])
# 绘制第一个子图,没有填充
plt.subplot(131)
plt.plot(fill_array)
plt.ylim([-0.5, 10.5])
# 绘制第二个子图,在竖直方向进行填充, facecolor为填充的颜色,alpha为透明度
plt.subplot(132)
plt.plot(fill_array)
plt.ylim([-0.5, 10.5])
plt.fill_between(x=range(10), y1=1, y2=fill_array, facecolor='red', alpha=0.5)
# 绘制第三个子图,在水平方向进行填充
plt.subplot(133)
plt.plot(fill_array)
plt.ylim([-0.5, 10.5])
plt.fill_betweenx(x1=0, x2=fill_array, y=range(10, 0, -1), facecolor='green', alpha=0.3)
plt.show()
填充效果展示