Skip to main content
 首页 » 编程设计

python之两条线之间的填充区域(当一条线低于另一条线时)

2025年05月04日12itcoder

运行时,显示的图形不会遮挡低于 5 的某些部分。我应该如何编辑它以使其覆盖整个区域?

import matplotlib.pyplot as plt 
 
x = [1,2,3,4,5,6,7,8,9,10] 
y = [4,9,1,3,6,2,4,7,6,3] 
z = [5]*len(y) 
 
plt.plot(x,y) 
plt.plot(x,z) 
plt.fill_between(x,y,z,where=[(y[i]<z[i]) for i in range(len(x))],facecolor='r') 
 
plt.show() 

请您参考如下方法:

如果您查看用于计算要填充的位置 的推导式,您会发现它仅检查您的y 和 中列出的点z 列表。但是,这些点之间也有一些区域需要填充。

此行为被提及 in the documentation :

Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersecion are simply clipped


你需要interpolate=True:

Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point

plt.fill_between( 
    x,y,z, 
    where=[(y[i]<z[i]) for i in range(len(x))], 
    facecolor='r', 
    interpolate=True 
) 

由于您还要求一种避免 5 列表的方法,您可以改用 axhline,并将列表切换为 numpy 便于比较的数组:

import matplotlib.pyplot as plt 
import numpy as np 
 
x = np.array([1,2,3,4,5,6,7,8,9,10]) 
y = np.array([4,9,1,3,6,2,4,7,6,3]) 
z = 5 
 
plt.plot(x,y) 
plt.axhline(y=z, color='orange') 
plt.fill_between(x,y,z,where=y<z, facecolor='r', interpolate=True) 
 
plt.show()