python - fill_between with matplotlib 和两个列表的 where 条件

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

并不是整个区域都被遮蔽了。

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

最佳答案

你完全正确,你需要插值。这非常复杂,因为您需要将 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()  

关于python - fill_between with matplotlib 和两个列表的 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533187/

相关文章:

python - 为什么这将 2 评估为素数?

python - 从 PIL 图像转换后,Numpy 数组不显示灰度图像的颜色尺寸

python - 可以在 matplotlib 的不同图中保持相同颜色的相同线条吗?

python - 如何使用Python请求使用offset参数对api调用进行分页

python - 如何让 pytest 等待(手动)用户操作?

python - Matplotlib 中的一半或四分之一极 map ?

python - 如何在 pyplot 中绘制每个 x 值的 y 轴平均值

python - matplotlib 中的频率轨迹

python 使用 matplotlib 绘制 json 文件数据

python - 在 python 中使用哪种策略进行多处理