在Google Colab中使用Matplotlib绘制CSV直方图报错求助
解决Matplotlib绘制CSV柱状图时的TypeError错误
问题原因
你的spc_common列中存在浮点数类型的值(大概率是CSV里的空单元格被pandas解析成了float类型的NaN),Matplotlib绘制柱状图时,x轴标签不允许混合字符串与浮点数类型,因此触发了TypeError: 'value' must be an instance of str or bytes, not a float错误。
解决步骤
- 排查数据问题
运行以下代码查看spc_common列的数据类型和空值数量:
print(df['spc_common'].dtype) print(df['spc_common'].isna().sum())
- 处理空值并统一类型
选择以下两种方式之一处理:
- 把空值替换为统一的字符串(比如"Unknown"):
df['spc_common'] = df['spc_common'].fillna('Unknown').astype(str)
- 或者直接删除包含空值的行:
df = df.dropna(subset=['spc_common']) df['spc_common'] = df['spc_common'].astype(str)
- 重新运行绘图代码
修改后再执行你的绘图代码即可正常生成柱状图:
fig, ax = plt.subplots(figsize=(50,10)) x = df['spc_common'] y = df['count'] plt.bar(x, height=y, align='center', width=0.8) plt.xlabel('Name of Trees (common name)', size=10) plt.ylabel('Number of Trees', size=10) pl.xticks(rotation=90) plt.show()
更简洁的替代方案
直接使用pandas内置的绘图功能,它会自动处理数据类型问题,代码更简洁:
df.plot(kind='bar', x='spc_common', y='count', figsize=(50,10), align='center', width=0.8) plt.xlabel('Name of Trees (common name)', size=10) plt.ylabel('Number of Trees', size=10) pl.xticks(rotation=90) plt.show()
内容的提问来源于stack exchange,提问作者Abiodun Adeoye
相关产品推荐
相关产品推荐

