使用matplotlib绘制填充的曲线图

matplotlib提供了两个比较方便的填充折线图的方式:

  1. 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,第二条曲线的节点的坐标值。
  1. 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的坐标
    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()

填充效果展示
填充效果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值