我正在尝试对由此示例代码生成的两条曲线的交点之前的区域进行着色:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100,10)
y1 = [0,2,4,6,8,5,4,3,2,1]
y2 = [0,1,3,5,6,8,9,12,13,14]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t_list,y1,linestyle='-')
ax.plot(t_list,y2,linestyle='--')
plt.show()
简单地使用:
ax.fill_between(x,y1,y2,where=y1>=y2,color='grey',alpha='0.5')
不工作并给出以下错误:“ValueError:参数维度不兼容”
我尝试将列表转换为数组:
z1 = np.array(y1)
z2 = np.array(y2)
然后:
ax.fill_between(x,y1,y2,where=z1>=z2,color='grey',alpha='0.5')
并不是整个区域都被遮蔽了。
我知道我必须通过插值找到两条曲线之间的交点,但还没有找到一种简单的方法来做到这一点。
最佳答案
你完全正确,你需要插值。这非常复杂,因为您需要将 interpolate=True
关键字参数添加到对 fill_between
的调用中。
ax.fill_between(x,y1,y2,where=z1>=z2,color='grey', interpolate=True)
要重现的完整代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100,10)
y1 = [0,2,4,6,8,5,4,3,2,1]
y2 = [0,1,3,5,6,8,9,12,13,14]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y1,linestyle='-')
ax.plot(x,y2,linestyle='--')
z1 = np.array(y1)
z2 = np.array(y2)
ax.fill_between(x,y1,y2,where=z1>=z2,color='grey',alpha=0.5, interpolate=True)
plt.show()
关于python - fill_between with matplotlib 和两个列表的 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533187/