代码之家  ›  专栏  ›  技术社区  ›  retorquere

matplotlib图表中感兴趣的阴影区域[重复]

  •  3
  • retorquere  · 技术社区  · 8 年前

    如果有这样的情节

    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)
    fig, ax = plt.subplots()
    ax.plot(s)
    ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
    ax.grid()
    plt.show()
    

    如果绘图的y值在(例如)1.25和0.75之间,如何自动对图表的垂直切片(从下到上)进行着色?

    正弦在这里只是一个样本,曲线图的实际值不太规则。

    我见过 FIll between two vertical lines in matplotlib ,看起来与这个问题类似,但答案在固定的x值之间有一个区域。我希望阴影区域由y值确定。

    2 回复  |  直到 8 年前
        1
  •  2
  •   sacuL    8 年前

    你可能在找 ax.fill_between ,这是非常灵活的(参见链接文档)。

    对于您的具体情况,如果我理解正确,这就足够了:

    fig, ax = plt.subplots()
    ax.plot(s)
    ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
    ax.fill_between(range(len(s)), min(s), max(s), where=(s < 1.25) & (s > 0.75), alpha=0.5)
    ax.grid()
    

    enter image description here

        2
  •  0
  •   heltonbiker    8 年前

    你可以用 ax.axvspan ,这显然正是你想要的。为了获得更好的效果,美国 alpha 值低于0.5,并可选择设置颜色和边缘颜色/宽度。

    fig, ax = plt.subplots()
    ax.plot(s)
    ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
    ax.axvspan(0.75, 1.25, alpha=0.2)
    ax.grid()
    plt.show()
    

    如果希望着色处于不同的方向(水平而不是垂直),还有 ax.axhspan 方法