遍历DataFrame列按数据类型绘图时出现“Rectangle无title属性”报错
遍历DataFrame列按类型绘图的报错解决
报错根因
- 原代码存在Python缩进错误:
for循环后的if判断语句未缩进,不符合Python代码块的语法要求,运行时会先触发IndentationError - 即便修正缩进,pandas的
Series.hist()方法本身未将title设为专属形参,直接向该方法传入title=column时,参数会被透传给matplotlib底层绘制直方图柱块的Rectangle类 Rectangle类不存在title属性,最终触发AttributeError: 'Rectangle' object has no property 'title'
可运行的修正代码
%matplotlib inline import matplotlib.pyplot as plt for column in df.columns: # 每列绘图前初始化独立画布和坐标轴,避免图像互相覆盖 fig, ax = plt.subplots() if df[column].dtype == "int64": # 直方图不传title参数,单独通过坐标轴设置图题 df[column].hist(ax=ax) ax.set_title(column) else: # bar图的plot接口原生支持title参数,可直接传入 df[column].plot(kind="bar", ax=ax, title=column)
优化提示
- 数值列类型判断可替换为
pd.api.types.is_numeric_dtype(df[column]),避免硬编码匹配int64导致float类型的数值列无法触发直方图绘制逻辑 - 可根据需求在
plt.subplots()中调整画布大小,避免多列绘图时图像比例失衡
内容的提问来源于stack exchange,提问作者Alessandro Mondin
相关产品推荐
相关产品推荐

