【问题标题】:Fill between y = 0 and positive values of y在 y = 0 和 y 的正值之间填充
【发布时间】:2015-06-10 19:48:21
【问题描述】:

我正在练习 matplotlib 函数的 fill_between。

我要做的是填充 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: Argument dimensions is incompatible。我检查了一些可能的解决方案,但无法正常工作。

【问题讨论】:

  • 看来 x、y1 和 y2 必须具有相同的维度,而您的情况并非如此。 ypos[2,4],而 x 有 5 个元素。我不确定这是否是您想要的,但您必须用数字填充 y 的非正值。类似ypos = [i if i > 0 else 0 for i in y]

标签: python python-3.x matplotlib


【解决方案1】:

你可以使用

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

产量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多