Python绘制2行3列5个直方图遇"dataframe object not callable"错误求助
解决"dataframe object not callable"错误并完成直方图绘制
错误原因
出现这个错误的核心原因是df4不是GroupBy对象,而是普通的DataFrame。只有GroupBy对象才有get_group()方法,直接在DataFrame上调用该方法会触发这个错误。另外,原代码没有指定绘图坐标轴,会导致每个直方图单独弹出窗口,无法在2行3列的布局中显示。
修正步骤与代码
1. 先创建GroupBy对象
首先需要对原始DataFrame按分类列(比如你的教育水平列,假设列名为education)进行分组:
# 假设原始数据框名为df,分类列是education df4 = df.groupby('education')
2. 指定绘图坐标轴
在调用plot()时,通过ax参数把直方图绑定到对应的subplot轴上,确保所有图都在同一个画布中:
import matplotlib.pyplot as plt plt.figure(figsize=(20, 8)) # 第一个子图 ax1 = plt.subplot(2, 3, 1) df4.get_group('Basic Level').plot(kind='hist', ax=ax1) ax1.set_title('Basic Level') # 第二个子图 ax2 = plt.subplot(2, 3, 2) df4.get_group("Doctorate").plot(kind='hist', ax=ax2) ax2.set_title('Doctorate') # 第三个子图 ax3 = plt.subplot(2, 3, 3) df4.get_group("Graduate").plot(kind='hist', ax=ax3) ax3.set_title('Graduate') # 第四个子图 ax4 = plt.subplot(2, 3, 4) df4.get_group("Illiterate").plot(kind='hist', ax=ax4) ax4.set_title('Illiterate') # 第五个子图 ax5 = plt.subplot(2, 3, 5) df4.get_group("Post Graduate").plot(kind='hist', ax=ax5) ax5.set_title('Post Graduate') # 调整子图间距,避免标题重叠 plt.tight_layout() plt.show()
额外说明
- 如果你的分类列名不是
education,替换成实际列名即可 - 给每个子图添加标题可以更清晰区分不同分组的直方图
tight_layout()会自动调整子图间距,避免元素重叠
内容的提问来源于stack exchange,提问作者Gaurav Tiwari
相关产品推荐
相关产品推荐

