fill_between与matplotlib和两个列表的where条件

时间:2017-10-02 20:24:17

标签: python matplotlib

我试图在此示例代码生成的两条曲线的交点之前对区域进行着色:

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')

并非整个区域都有阴影。

我知道我必须通过插值找到两条曲线之间的交点,但还没有看到一种简单的方法。

1 个答案:

答案 0 :(得分:3)

你是完全正确的,你需要插值。这非常复杂,因为您需要在interpolate=True的调用中添加fill_between关键字参数。

ax.fill_between(x,y1,y2,where=z1>=z2,color='grey', interpolate=True)

enter image description here

完整的代码重现:

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