我正在try 使用matplotlib填充两条相交线下方和两条线上方的区域.我可以在两行之间填充,但还没有找到一种简单的方法来反转之前获得的区域.我唯一的解决办法是创建一些额外的函数(底部的一个低的,最小的一个,顶部的类似功能),这有点麻烦,需要手动输入(见下文).有更好的解决方案吗?

Illustration

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

编辑:按照@Mad物理学家的建议交换BG和FG colored颜色 将在基本情况下有效,但如果有几个这样的区域要叠加则不起作用

推荐答案

看起来fill_between不适合无限大的值(例如Fill area under curve in matlibplot python on log scale).但是,如果您只想绘制这些特定的线条,则只需反转绘图的 colored颜色 即可:

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

enter image description here

这是非常繁琐的,不会很好地与交互情节一起工作,但它将显示您想要的情节,希望相当轻松.

enter image description here

一种稍微好一点的方法可能是仅将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()

enter image description here

Python相关问答推荐

将两个收件箱相连导致索引的列标题消失

如何分割我的收件箱,以便连续的数字各自位于自己的收件箱中?

为什么我的(工作)代码(生成交互式情节)在将其放入函数中时不再工作?

如何在vercel中指定Python运行时版本?

如何使用Tkinter创建两个高度相同的框架(顶部和底部)?

使用多个性能指标执行循环特征消除

Python中的函数中是否有充分的理由接受float而不接受int?

跟踪我已从数组中 Select 的样本的最有效方法

在Pandas 日历中插入一行

基于索引值的Pandas DataFrame条件填充

joblib:无法从父目录的另一个子文件夹加载转储模型

字符串合并语法在哪里记录

用砂箱开发Web统计分析

无法连接到Keycloat服务器

如何更新pandas DataFrame上列标题的de值?

如何使用SentenceTransformers创建矢量嵌入?

如何在FastAPI中为我上传的json文件提供索引ID?

在Python中计算连续天数

Python Pandas—时间序列—时间戳缺失时间精确在00:00

具有相同图例 colored颜色 和标签的堆叠子图