首页 > 解决方案 > 如何在python中的3行之间使用fill_between

问题描述

我有一个包含我的 limit_up 值的列表,一个包含 limit_down 值的列表,以及一个填充了“100”值的第三个列表(其他列表的大小相同)。我想将limit_up和100之间的区域设置为绿色,将(100或limit_up)和limit_down之间的区域设置为红色',如下图所示。

但是,有时,由于我的 limit_down 列表没有任何低于 100 的值,因此该区域需要完全绿色。当我所有的 limit_up 值都低于 100 时,也会发生同样的情况,该区域需要全红。有人可以帮忙吗?

图片在这里

左图数据:

limit_down = ['8.5', '37.5', '45.2', '51.9', '55.0', '55.2', '56.7']
limit_up = ['982.6', '393.3', '286.2', '260.4', '232.9', '200.0', '201.7']
reference = [100 100 100 100 100 100 100]

右图数据:

limit_down = ['265.0', '649.1', '804.0', '895.1', '874.2', '957.9', '976.4']
limit_up = ['23815.5', '9043.4', '6932.4', '5805.6', '4510.5', '4317.5', '3963.5']
reference = [100 100 100 100 100 100 100]

标签: pythonpython-3.xmatplotlib

解决方案


fill_between和 numpy 的数组过滤可以如下使用来创建这些图:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 35, 7)
limit_down_1 = np.array([8.5, 37.5, 45.2, 51.9, 55.0, 55.2, 56.7])
limit_up_1 = np.array([982.6, 393.3, 286.2, 260.4, 232.9, 200.0, 201.7])
reference = 100

limit_down_2 = np.array([265.0, 649.1, 804.0, 895.1, 874.2, 957.9, 976.4])
limit_up_2 = np.array([23815.5, 9043.4, 6932.4, 5805.6, 4510.5, 4317.5, 3963.5])

fig, axes = plt.subplots(ncols=2, figsize=(12, 4))
for ax, limit_up, limit_down in zip(axes, [limit_up_1, limit_up_2], [limit_down_1, limit_down_2]):
    ax.fill_between(x, np.maximum(reference, limit_down), limit_up, color='limegreen', alpha=0.3,
                    where=limit_up > reference, interpolate=True)
    ax.fill_between(x, limit_down, np.minimum(reference, limit_up), color='crimson', alpha=0.3,
                    where=limit_down < reference, interpolate=True)
    for y in (limit_up, limit_down):
        ax.plot(x[y <= reference], y[y <= reference], color='crimson')
        ax.plot(x[y >= reference], y[y >= reference], color='limegreen')
plt.show()

结果图


推荐阅读