numpy 使用axline作为输入的fill_between函数生成TypeError

jaxagkaj  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(112)

我尝试使用axline作为matplotlib(版本3.4.3)fill_between()函数的输入之一。下面是简化的代码示例代码。

验证码:

import numpy as np
import matplotlib.pyplot as plt

# Set my figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]

# Define a linear space between -5 and 5, with 100 points
x = np.linspace(-5, 5, 100)

# Define the Intercept and Slope
intercept0 = 2.2
slope0 = 0.75

# Set the x and y limits for the plot
plt.xlim(-5,5)
plt.ylim(-5,5)

# Create a diagonal line through [0,2.2] with a slope of 0.75
diagline = plt.axline((0,intercept0), slope=slope0, color='C0')

# Fill the area between the diagonal line and y=0
plt.fill_between(x,diagline,0)

plt.show()

当我运行这段代码时,我得到以下numpy错误。

错误:

TypeError:ufunc 'isfinite'不支持输入类型,并且无法根据强制转换规则'' safe ''将输入安全地强制转换为任何受支持的类型
有没有办法将axline用作fill_between()函数的输入?我见过垂直线和水平线用作fill_between()的输入,以及曲线(西内斯),但我找不到用axline创建对角线的示例。

wgx48brx

wgx48brx1#

直线的方程就是slope0 * x + intercept0,numpy可以不加修改地使用它。所以,你可以用plt.fill_between(x, slope0 * x + intercept0)来填充。

import numpy as np
import matplotlib.pyplot as plt

# Set my figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]

# Define a linear space between -5 and 5, with 100 points
x = np.linspace(-5, 5, 100)

# Define the Intercept and Slope
intercept0 = 2.2
slope0 = 0.75

# Set the x and y limits for the plot
plt.xlim(-5, 5)
plt.ylim(-5, 5)

# Create a diagonal line through [0,2.2] with a slope of 0.75
diagline = plt.axline((0, intercept0), slope=slope0, color='C0')

# Fill the area between the diagonal line and y=0
plt.fill_between(x, slope0 * x + intercept0, 0, facecolor='gold', alpha=0.4, edgecolor='r', hatch='xx')
plt.show()

PS:如果你只想显示正面的部分,你可以使用where参数:

y0 =  slope0 * x + intercept0
plt.fill_between(x, y0, 0, where=y0 >= 0, interpolate=True, color='yellow')
plt.axhline(0, color='black') # shows the x-axis at y=0

相关问题