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

Python使用matplotlib绘图无数据显示问题求助

解决Python数据可视化空图表问题

问题根源及修复方案

  • plot变量传参错误
    你在plt.plot(hight, c='red')中传入了单个临时变量hight,而非存储所有温度数据的列表hights。hight仅保存循环最后一次的临时值(或报错后无有效值),导致绘图时没有完整数据可展示。

  • try-except范围错误
    当前把整个for循环包裹在try块内,只要某一行转换int类型报错,整个循环就会终止并执行pass,后续所有数据行都不会被处理,直接导致hights列表为空。正确做法是将try-except放在循环内部,仅跳过出错的单行数据。

  • 可选:变量名拼写规范
    hights应为highs(符合英文拼写习惯,避免后续混淆)。


修改后的代码

import csv
from matplotlib import pyplot as plt

filename = 'sitka_weather_2014.csv'

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    highs = []  # 修正变量名拼写
    
    for row in reader:
        try:
            high = int(row[1])
            highs.append(high)
        except ValueError:
            print(f"跳过无效数据行: {row}")  # 可选:打印错误行辅助排查
    
print(highs)
     
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(highs, c='red')  # 传入完整数据列表highs

plt.title('Daily high temperature, July 2014', fontsize=24)
plt.xlabel('', fontsize=16)
plt.ylabel('Temperature (F)', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)

plt.show()

额外排查建议

如果修改后仍无数据,需确认CSV文件中row[1]是否对应最高温度列。可添加print(header_row)查看表头,根据输出找到正确的列索引(比如row[2])替换即可。

内容的提问来源于stack exchange,提问作者user19976311

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:05:29