You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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错误。

解决步骤

  1. 排查数据问题
    运行以下代码查看spc_common列的数据类型和空值数量:
print(df['spc_common'].dtype)
print(df['spc_common'].isna().sum())
  1. 处理空值并统一类型
    选择以下两种方式之一处理:
  • 把空值替换为统一的字符串(比如"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)
  1. 重新运行绘图代码
    修改后再执行你的绘图代码即可正常生成柱状图:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:10:56