【问题标题】:Matplotlib fill_between function using axline as input generates TypeErrorMatplotlib fill_between 函数使用 axline 作为输入生成 TypeError
【发布时间】:2021-12-16 11:37:29
【问题描述】:

我正在尝试使用 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 创建的对角线示例。

【问题讨论】:

  • fill_between 想要一个数字数组,而不是艺术家
  • @PaulH 谢谢,这是有道理的。是否可以计算艺术家(轴)与 x 或 y 限制相交的位置?我可以用它来为 y 生成一个 linspace。没关系,我只是回答了我自己的问题。我有斜坡和起始相交。这只是一个简单的几何问题。
  • 我会直接从您现有的 x 变量中计算该行的 y 值

标签: python numpy matplotlib plot


【解决方案1】:

线的方程就是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

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多