Python:在三条曲线之间填充

2024-10-02 02:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三条曲线,我想在它们之间填充:

enter image description here

我正在使用以下代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

a=np.arange(-5,300,2)

def f(a): return a**2

def slope(a):
  slope=2*(a)
  return slope

xp = 60
yp = f(xp)
def line(a, xp, yp):
    return slope(xp)*(a - xp) + yp
plt.plot(a, f(a))
plt.scatter(xp, yp, color='C1', s=50)
plt.plot(a, line(a, xp, yp), 'C1--', linewidth = 2)
    
xp1=250
yp1=f(xp1)

plt.scatter(xp1, yp1, color='C1', s=50)
plt.plot(a, line(a, xp1, yp1), 'C3--', linewidth = 2)

plt.fill_between(a,f(a),line(a, xp1, yp1),line(a, xp, yp),color='green')

plt.show()

输出为:

enter image description here

我想要一个填充限制,它是yp1yp。 我尝试在fillbetween命令中使用where参数,如下所示:

plt.fill_between(a,f(a),line(a, xp1, yp1),line(a, xp, yp),where=[(a>yp)and (a<yp1) for a in a],color='green')

但是由于某种原因,我得到了这个错误:TypeError: fill_between() got multiple values for argument 'where'

有什么帮助或想法吗


Tags: importreturnplotdefaslinepltfill
1条回答
网友
1楼 · 发布于 2024-10-02 02:24:24

错误TypeError: fill_between() got multiple values for argument 'where'源于您提供了两次where,因为fill_between的签名是Axes.fill_between(self, x, y1, y2=0, where=None, ...)。在代码中,line(a, xp, yp)作为where提供

除了使用where=(a > yp) & (a < yp1)限制两点之间的填充区域外,您实际上要做的是仔细选择y1y2限制

enter image description here

我已经把变量的名称改了一点,使之更具可读性。数组以大写字母开头,单个值为小写

import numpy as np
import matplotlib.pyplot as plt

def f(X):
    return X**2

def slope(x):
  return 2*x

def line(X, xp, yp):
    return slope(xp)*(X - xp) + yp

fig, ax = plt.subplots()
X = np.arange(-5, 300, 2)

Y0 = f(X)
ax.plot(X, Y0)

x_left = 60
y_left = f(x_left)
Y1 = line(X, x_left, y_left)
ax.scatter(x_left, y_left, color='C1', s=50)
ax.plot(X, Y1, 'C1 ', linewidth = 2)

x_right = 250
y_right = f(x_right)
Y2 = line(X, x_right, y_right)
ax.scatter(x_right, y_right, color='C1', s=50)
ax.plot(X, Y2, 'C3 ', linewidth = 2)

where = (x_left < X) & (X < x_right)
Ylower = [max(y1, y2) for (y1, y2) in zip(Y1, Y2)]
ax.fill_between(X, Ylower, Y0, where=where, color='green')

fig.show()

相关问题 更多 >

    热门问题