【问题标题】:Python:Fill between three curvesPython:在三条曲线之间填充
【发布时间】:2021-03-02 21:33:25
【问题描述】:

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

我正在使用此代码:

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

输出是:

我想要一个填充限制,即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'

有什么帮助或想法吗?

【问题讨论】:

    标签: python python-3.x pandas matplotlib google-colaboratory


    【解决方案1】:

    错误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 &gt; yp) &amp; (a &lt; yp1) 来限制两个点之间的填充区域之外,您实际上要做的是仔细选择y1y2 限制。

    我已将变量名称更改为我觉得更易读的名称。数组以大写字母开头,单个值小写。

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

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2016-05-16
      相关资源
      最近更新 更多