繁体   English   中英

Matplotlib fill_between 反转?

[英]Matplotlib fill_between invert?

我正在尝试使用 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 colors 将起作用@Mad Physicist,但如果有几个这样的区域要覆盖,则不会

似乎fill_between不能很好地处理无限值(例如,在 matlibplot python on log scale 的曲线下填充区域)。 但是,如果您只是尝试 plot 那些特定的行,您可以反转 plot 的 colors:

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 并且不适用于交互式绘图,但它会显示您想要的 plot,希望相当轻松。

在此处输入图像描述

更好的方法可能是将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()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM