matplotlib错误

2024-09-22 16:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据

city    inc pop edu crime   cult
New-York    29343,00    8683,00 0,00    10,40   0,00
Moscow  25896,00    17496,00    0,00    10,20   1,0
Rome    21785,00    15063,00    0,00    14,20   1,00
London  20000,00    70453,00    1,00    18,00   1,00
Berlin  44057,00    57398,00    1,00    6,30    1,00

我尝试构建plot并给plot命名,并将颜色更改为列

^{pr2}$

但它返回错误AttributeError: 'module' object has no attribute 'set_title'TypeError: 'AxesSubplot' object has no attribute '__getitem__'


Tags: 数据nocitynewobjectplotattributepop
2条回答

您试图使用AxesSubplot类中的set_title方法,但是您没有使用mpl面向对象的方法。有两种方法可以纠正这种情况:

  1. 使用plt.title('Salary and culture')

  2. 切换到更灵活的OO方法,并使用相关的Axes方法设置标题和轴标签,例如ax.set_titleax.set_xlabel,等等。

第二个错误的来源是,在对pivot_table调用.plot时,返回的是matplotlib AxesSubplot对象,而不是DataFrame。因此,您尝试绘制result[[0]],它试图索引AxesSubplot对象。在

desire_salary = (df[(df['inc'] >= int(salary_people))])
fig = plt.figure()

# Create the pivot_table
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')

# plot it in a separate step. this returns the matplotlib axes
ax = result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre", ax=ax)

ax.set_xlabel("Cultural centre")
ax.set_ylabel("Frequency")
ax.set_title('Salary and culture')

ax.plot(result[[0]], color='red')
ax.plot(result[[1]], color='blue')
plt.show()

尝试为TypeError“return”type='dict'“error:”AxesSubplot'对象没有属性'getitem'

相关问题 更多 >