【问题标题】:How to partial fill_between in matplotlib, as in different colors for different values如何在matplotlib中部分填充_between,如不同值的不同颜色
【发布时间】:2020-02-09 03:14:39
【问题描述】:

我正在尝试为图形线和 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 轴之间的空间始终是基于数组中第一个值的颜色(在本例中为红色)。我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x matplotlib graph colors


    【解决方案1】:

    使用numpyA &gt; B。否则,如果不想使用 numpy,则需要为 [a &gt; 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()
    

    【讨论】:

    • 谢谢。我没有注意到我应该使用 numpy 数组。也感谢您在不使用 numpy 的情况下包含该方法。如果值在 95 到 100 之间,我用那个填充第三种颜色。不过,快速附加问题,我怎样才能摆脱颜色之间的空白。 (i.imgur.com/keObOfn.png)。如果可以的话
    猜你喜欢
    • 2017-02-28
    • 2022-11-24
    • 1970-01-01
    • 2020-02-13
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多