matplotlib 如何反转fill_between

n6lpvg4x  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(101)

我尝试使用matplotlib填充两条相交线下方和两条线上方的区域。我可以在两条线之间填充,但还没有找到一种简单的方法来反转之前获得的区域。唯一的解决方法是创建一些额外的函数。(一个低的和一个最小的底部,和顶部的等价物),这是一个有点麻烦,需要手动输入(见下文)。

import numpy as np
import matplotlib.pyplot as plt

# Doesn't work
def f1(x): return 32.0 * x + 2.0
def f2(x): return -55.0 * x
xRng=[-1, 1]
plt.plot(xRng, [f1(x) for x in xRng], 'b-')
plt.plot(xRng, [f2(x) for x in xRng], 'r-')
plt.fill_between(xRng, [f1(x) for x in xRng], [f2(x) for x in xRng], color='g') # Would like the fill inverted
plt.title('Not good'); plt.show()

# Works, but clumsy
def fLo(x): return -100
def fHi(x): return 100
def fMin(x): return min(f1(x), f2(x))
def fMax(x): return max(f1(x), f2(x))
xRng=np.linspace(-1, 1, 100)
plt.plot(xRng, [f1(x) for x in xRng], 'b-')
plt.plot(xRng, [f2(x) for x in xRng], 'r-')
plt.fill_between(xRng, [fMin(x) for x in xRng], [fLo(x) for x in xRng], color='g')
plt.fill_between(xRng, [fMax(x) for x in xRng], [fHi(x) for x in xRng], color='g')
plt.title('Complicated'); plt.show()

编辑:交换BG和FG颜色的建议,@疯狂的物理学家将工作,如果基本的情况下,但如果有几个这样的领域覆盖

kxeu7u2r

kxeu7u2r1#

看起来fill_between不能很好地处理无限值(例如Fill area under curve in matlibplot python on log scale)。但是,如果你只想绘制那些特定的线,你可以反转图的颜色:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)
y1 = 32.0 * x + 2.0
y2 = -55.0 * x

fig, ax = plt.subplots()
ax.set_facecolor('g')
ax.plot(x, y1, 'b-')
ax.plot(x, y2, 'r-')
ax.fill_between(x, y1, y2, color='w')
ax.set_xlim(x.min(), x.max())
plt.show()

这是非常hacky和不会与互动的情节很好地工作,但它会显示你想要的情节,希望相当无痛。

一个稍微好一点的方法可能是只将x覆盖的区域的背景设置为绿色补丁:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 100)
y1 = 32.0 * x + 2.0
y2 = -55.0 * x

fig, ax = plt.subplots()
ax.plot(x, y1, 'b-')
ax.plot(x, y2, 'r-')
ax.axvspan(x.min(), x.max(), color='g')
ax.fill_between(x, y1, y2, color='w')
ax.set_xlim(x.min(), x.max())
plt.show()

相关问题