簡體   English   中英

如何在 matplotlib 中部分填充_between,如在不同的 colors 中用於不同的值

[英]How to partial fill_between in matplotlib, as in different colors for different values

我正在嘗試為圖形線和 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()

結果如下圖: 在此處輸入圖像描述

值小於 100 的區域應該是綠色的。 但線和 x 軸之間的空間始終是基於數組中第一個值的顏色(在本例中為紅色)。 我怎樣才能解決這個問題?

使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM