python - 在 y = 0 和 y 的正值之间填充

标签 python python-3.x matplotlib

我正在练习 fill_ Between matplotlib 函数。

我想要做的是填充 y = 0 和 y 的正值之间的区域,并让 y = 0 和 y 的负值之间的区域不填充。

类似于:

import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [0,2,-3,4,-5]

ypos = [i for i in y if i>0]

plt.plot(x,y)
plt.fill_between(x,0,ypos)
plt.show()

它给出的错误是ValueError:参数维度不兼容。我已经检查了一些可能的解决方案,但无法使其正常工作。

最佳答案

你可以使用

where=np.array(y)>0

限制填充区域的绘制位置并使用

interpolate=True

fill_between找到交点:

<小时/>
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5])
y = np.array([0,2,-3,4,-5])
plt.plot(x,y)
plt.fill_between(x, 0, y, where=y>0, interpolate=True)
plt.show()

产量

enter image description here

关于python - 在 y = 0 和 y 的正值之间填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30765932/

相关文章:

python - "pylint (import error)"在与 VSCode 相同的文件夹中导入模块时

python - Python 中的高效可视化

python - 如何调整matplotlib中每第二行子图之间的空间

python-3.x - 如何使用 matplotlib 绘制半圆

python - 如何从 numpy 矩阵中删除 nan 和 inf 值?

python - 对一列进行分组,使其每组中的总和大致相等

Python Selenium 多线程问题

python - 如何修复 python 3.7.1 上的导入 TensorFlow 错误?

python - 读取 Flask Web 服务的参数

python - 改用 IPython 和 Spyder 复制 jupyter HTML 输出