如何在matplotlib中部分填充之间,如不同值的不同颜色

Swe*_*gin 3 graph colors matplotlib python-3.x

我正在尝试为图形线和 x 轴之间的空间着色。颜色应基于线上对应点的值。有点像第一张图: 在此输入图像描述https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/fill_ Between_demo.html

如果高于 100,则应为红色;如果低于 100,则应为绿色。我正在寻找的图表应该是红绿交替的。

这就是我现在所拥有的:

import matplotlib.pyplot as plt

lenght = 120

y = [107, 108, 105, 109, 107, 106, 107, 109, 106, 106, 94, 93, 94, 93, 93, 94, 95, 106, 108, 109, 107, 107, 106, 108, 105, 108, 107, 106, 107, 97, 93, 96, 94, 96, 95, 94, 104, 107, 106, 108, 107, 107, 106, 107, 105, 107, 108, 105, 107, 100, 93, 94, 93, 95, 104, 107, 107, 108, 108, 107, 107, 107, 107, 104, 94, 96, 95, 96, 94, 95, 94, 100, 107, 107, 105, 107, 107, 109, 107, 108, 107, 105, 108, 108, 106, 97, 94, 94, 94, 94, 95, 94, 94, 94, 96, 108, 108, 107, 106, 107, 107, 108, 107, 106, 95, 95, 95, 94, 94, 96, 105, 108, 107, 106, 106, 108, 107, 108, 106, 107]

x = [x for x in range(lenght)]

lvl = lenght * [100]

fig, ax = plt.subplots()

ax.plot(x, y, color="black")
ax.fill_between(x, 0, y, where=y>lvl, facecolor='red', interpolate=True)
ax.fill_between(x, 0, y, where=y<=lvl, facecolor='green', interpolate=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果如下图所示: 在此输入图像描述

值小于 100 的区域应该是绿色的。但线条和 x 轴之间的空间始终是基于数组中第一个值的颜色(在本例中为红色)。我怎样才能解决这个问题?

Imp*_*est 5

使用numpyA > B。否则,如果不想使用 numpy,则需要使用[a > b for a,b in zip(A,B)].

import numpy as np
import matplotlib.pyplot as plt

y = [107, 108, 105, 109, 107, 106, 107, 109, 106, 106, 94, 93, 94, 93, 93, 94, 95, 106, 108, 
     109, 107, 107, 106, 108, 105, 108, 107, 106, 107, 97, 93, 96, 94, 96, 95, 94, 104, 107, 
     106, 108, 107, 107, 106, 107, 105, 107, 108, 105, 107, 100, 93, 94, 93, 95, 104, 107, 107, 
     108, 108, 107, 107, 107, 107, 104, 94, 96, 95, 96, 94, 95, 94, 100, 107, 107, 105, 107, 107, 
     109, 107, 108, 107, 105, 108, 108, 106, 97, 94, 94, 94, 94, 95, 94, 94, 94, 96, 108, 108, 107, 
     106, 107, 107, 108, 107, 106, 95, 95, 95, 94, 94, 96, 105, 108, 107, 106, 106, 108, 107, 
     108, 106, 107]
y = np.array(y)
x = np.arange(len(y))

lvl = 100

fig, ax = plt.subplots()

ax.plot(x, y, color="black")
ax.fill_between(x, 0, y, where=y>lvl, facecolor='red', interpolate=True)
ax.fill_between(x, 0, y, where=y<=lvl, facecolor='green', interpolate=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)