You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib报错‘list object has no attribute add_subplot’的修正方法

问题:运行Python代码出现‘list object has no attribute add_subplot’错误如何修正?

我已参考其他帖子的建议,但运行以下代码仍出现‘list object has no attribute add_subplot’错误,请问该如何修正?

import numpy as np 
import seaborn as sns
import matplotlib.pyplot as plt


#create data
x = np.array([4.1,7.1,5.2,7.1,0.3, 8.3, 9.7, 8.2])
y = np.array([0.7,0.72,0.5,0.73, 0.65, 0.57, 0.7, 0.8])

#create basic scatterplot
plt.plot(x, y, 'o',markersize=10,c='black')

#obtain m (slope) and b(intercept) of linear regression line
m, b = np.polyfit(x, y, 1)

#add linear regression line to scatterplot 
fig = plt.plot(x, m*x+b)
ax = fig.add_subplot(111)
ax.set_ylim([0.45,0.8])

sns.despine(top=True, right=True, left=False, bottom=False)
plt.xlabel('Accuracy', fontsize=22)
plt.ylabel('Score', fontsize=22)

解决方案

错误原因

plt.plot()函数返回的是Line2D对象的列表,并非matplotlib的Figure对象,所以调用fig.add_subplot()时会触发“列表没有add_subplot属性”的错误。

修正方案

改用matplotlib的面向对象API操作,先创建Figure和Axes对象,再通过Axes完成绘图、参数设置等操作,避免全局函数与对象方法混用导致的类型混淆。

修正后的代码

import numpy as np 
import seaborn as sns
import matplotlib.pyplot as plt

# 创建数据
x = np.array([4.1,7.1,5.2,7.1,0.3, 8.3, 9.7, 8.2])
y = np.array([0.7,0.72,0.5,0.73, 0.65, 0.57, 0.7, 0.8])

# 创建Figure和Axes对象
fig, ax = plt.subplots()

# 绘制散点图
ax.plot(x, y, 'o', markersize=10, c='black')

# 计算线性回归的斜率和截距
m, b = np.polyfit(x, y, 1)

# 绘制回归线
ax.plot(x, m*x + b, c='black')

# 设置y轴范围
ax.set_ylim([0.45, 0.8])

# 移除指定边框
sns.despine(top=True, right=True, left=False, bottom=False)

# 设置坐标轴标签
ax.set_xlabel('Accuracy', fontsize=22)
ax.set_ylabel('Score', fontsize=22)

# 显示图像
plt.show()

补充说明

如果习惯使用pyplot全局函数,也可以直接替换错误代码段,无需创建Axes对象:

# 替换原错误代码
plt.plot(x, m*x+b)
plt.ylim([0.45,0.8])

内容的提问来源于stack exchange,提问作者Pugl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:35:20