【问题标题】:matplotlib fill_between with discrete x-values and where parameter produces gapsmatplotlib fill_between 具有离散的 x 值以及参数产生间隙的位置
【发布时间】:2021-04-08 00:11:36
【问题描述】:

我正在尝试创建一个区域图,其中填充根据 y 值发生变化。使用fill_between 和where 参数大多有效,但会留下未填充的区域:

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(1,10)
y=np.array([1,4,6,8,4,7,5,6,0])

plt.plot(x, y, color='black')
plt.fill_between(x, y, where=y < 5, color='red')
plt.fill_between(x, y, where=y >= 5, color='blue')

plt.show()

Run on trinket.io

产生这个结果:Plot without interpolation

如何去除图表下方的任何白色区域?对于当前的“中间”区域应该如何着色,我没有严格的要求。在中点会面——或两者兼而有之——都行。

添加interpolate=True 在某些方面略微改善了这种情况,但在其他方面看起来更加混乱:Plot with interpolation

我查看了step 参数,但在我看来这似乎并不乐观。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    由于您的要求很简单,最好的方法可能是确定您的“默认”颜色并将其用作整个曲线的 fill_between 而不指定任何条件。最重要的是,您可以为不同的条件添加不同的颜色。比如:

    fig, ax = plt.subplots()
    
    ax.fill_between(x, y, color="blue")
    ax.fill_between(x, y, where=y<=5, color="red")
    

    它给出以下输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2022-01-01
      • 2016-06-25
      • 2011-02-05
      • 1970-01-01
      相关资源
      最近更新 更多