“list”对象在matplotlib中没有属性“add_subplot”

yiytaume  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(150)

我已经按照另一个威胁的建议,但这段代码仍然给我列表对象没有没有属性的错误-什么是纠正?

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

ars1skjm1#

在线上

fig = plt.plot(x, m*x+b)

plt.plot函数返回Line2d对象列表,而不是Figure对象。我建议执行以下操作:

fig, ax = plt.subplots()  # create figure and axes

# plot on ax (Axes) object
ax.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 
ax.plot(x, m*x+b)
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)
1wnzp6jl

1wnzp6jl2#

错误是因为图add_subplot(111)没有返回轴对象,而是从plt.plot(x,m*x+b)返回Line2D对象。用fig,ax = plt.subplots()替换该行以创建图形和轴对象,然后使用ax.set_ylim([0.45,0.8])设置y限制。此外,应在plt.xlabel()和plt.ylabel()之后调用sns.despine()

#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, ax = plt.subplots()
plt.plot(x, m*x+b)
ax.set_ylim([0.45,0.8])

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

相关问题