Matplotlib绘图报错:'function'对象无'xlabel'属性,图表无轴标签及标题
问题解决:AttributeError及图表标签/标题不显示问题
错误原因及修复步骤:
导入方式错误
你最初的import matplotlib as plt是错误的,xlabel等绘图方法属于matplotlib.pyplot模块,必须正确导入:import matplotlib.pyplot as plt列名操作错误
代码中shelter_df['Animal', 'Age Range at Intake']会创建一个多级索引列,但你只是想转换Age Range at Intake列的类型,应改为直接操作该列:shelter_df['Age Range at Intake'] = shelter_df['Age Range at Intake'].astype(str)多余的画布创建
你在创建ax之后又调用了plt.figure(figsize=(12,6)),这会生成一个新的空白画布,而你设置的轴标签、标题都在之前的画布上,最终显示的是新空白画布,所以看不到内容,需要删除这行代码。方法调用语法错误
ax.get.xticklabels()是语法错误,正确的方法是ax.get_xticklabels()(用下划线替代点号)。
修正后的完整代码:
import pandas as pd import matplotlib.pyplot as plt # 确保'Age Range at Intake'列为字符串类型 shelter_df['Age Range at Intake'] = shelter_df['Age Range at Intake'].astype(str) # 筛选领养数据 adoptionData = shelter_df[shelter_df['Outcome Type'] == 'Adoption'] # 按入所年龄组和动物类型分组统计 ageAnimalAdoptCounts = adoptionData.groupby(['Age Range at Intake', 'Animal']).size().unstack() # 绘制堆叠条形图 ax = ageAnimalAdoptCounts.plot(kind='bar', stacked=True, figsize=(12, 6)) # 设置轴标签和标题 ax.set_xlabel('Age Range at Intake') ax.set_ylabel('Count') ax.set_title('Animal Types adopted per Age Group at Intake') # 设置x轴标签旋转 ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Querty
相关产品推荐
相关产品推荐

