将axline作为fill_between输入触发TypeError的问题咨询
解决方案
首先明确:无法直接将axline的返回值作为fill_between()的输入参数,原因如下:
plt.axline()返回的是matplotlib.lines.Line2D类型的图形对象,不是fill_between()要求的数值型数组fill_between()的第二、第三位置参数需要传入和第一个参数x长度匹配的y轴数值序列,传入图形对象会触发类型校验报错
正确实现方式
你已经提前定义了斜率和截距,直接用该参数计算对应x序列的y值即可,修改后完整代码如下:
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') # 计算斜线对应的y值序列再传入fill_between y_diag = slope0 * x + intercept0 plt.fill_between(x, y_diag, 0) plt.show()
如果未提前保存斜率和截距,也可以从axline返回的对象中读取参数再计算:
# 从diagline对象读取斜率、截距 slope = diagline.get_slope() intercept = diagline.get_intercept() y_diag = slope * x + intercept plt.fill_between(x, y_diag, 0)
内容的提问来源于stack exchange,提问作者JamCon
相关产品推荐
相关产品推荐

