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

如何用Pandas读取CSV数据绘制4种Matplotlib天气指标可视化图表?

解决天气数据可视化异常问题 + Pandas读取CSV绘制4种Matplotlib图表示例

先解决图表异常、数据不显示的常见问题

  • 检查CSV数据格式:日期列如果是字符串,读取时没转成datetime会导致x轴顺序混乱;数值列如果夹杂空格、单位(比如"23℃")会被识别成字符串,无法绘图。
    • 处理代码:读取时指定解析日期列,批量转数值类型并清理无效值:
      df = pd.read_csv('weather_data.csv', parse_dates=['date'], index_col='date')
      for col in ['temp', 'wind_speed', 'humidity', 'pressure']:
          df[col] = pd.to_numeric(df[col], errors='coerce')
      df = df.dropna()
      
  • 检查数据范围:如果某列数值波动极大(比如气压是千级,气温是几十级),共用y轴会导致小数值列被压缩看不见,建议用子图或双y轴分开绘制。
  • 检查图表类型匹配:比如用柱状图展示高频时间序列数据会挤成一团,换成折线图更合适;散点图不要用来展示时间序列趋势。

Pandas读取CSV绘制4种Matplotlib图表示例

假设你的CSV列名为date(日期)、temp(气温)、wind_speed(风速)、humidity(相对湿度)、pressure(气压),先执行上面的数据清洗代码,再运行以下图表代码:

1. 多折线图(展示气温、气压随时间变化)

适合对比不同时间序列的趋势:

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
plt.plot(df.index, df['temp'], label='气温(℃)', color='red')
plt.plot(df.index, df['pressure'], label='气压(hPa)', color='blue')
plt.xlabel('日期')
plt.ylabel('数值')
plt.title('气温与气压随时间变化')
plt.legend()
plt.xticks(rotation=45)  # 旋转日期标签避免重叠
plt.tight_layout()  # 自动调整布局
plt.show()

2. 柱状图(展示每日平均相对湿度)

适合展示离散时段的统计值:

# 如果是小时级数据,先按天取平均值
daily_humidity = df['humidity'].resample('D').mean()

plt.figure(figsize=(12, 6))
daily_humidity.plot(kind='bar', color='green')
plt.xlabel('日期')
plt.ylabel('平均相对湿度(%)')
plt.title('每日平均相对湿度')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

3. 散点图(气温与相对湿度的相关性)

适合展示两个变量的关联关系:

plt.figure(figsize=(10, 6))
plt.scatter(df['temp'], df['humidity'], alpha=0.6, color='purple')
plt.xlabel('气温(℃)')
plt.ylabel('相对湿度(%)')
plt.title('气温与相对湿度的相关性')
plt.grid(True)
plt.show()

4. 多子图组合(同时展示四种气象数据)

适合一次性呈现所有指标的趋势:

fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# 子图1:气温
axes[0,0].plot(df.index, df['temp'], color='red')
axes[0,0].set_title('气温变化')
axes[0,0].set_xlabel('日期')
axes[0,0].set_ylabel('℃')
axes[0,0].tick_params(axis='x', rotation=45)

# 子图2:风速
axes[0,1].plot(df.index, df['wind_speed'], color='orange')
axes[0,1].set_title('风速变化')
axes[0,1].set_xlabel('日期')
axes[0,1].set_ylabel('m/s')
axes[0,1].tick_params(axis='x', rotation=45)

# 子图3:湿度
axes[1,0].bar(df.index, df['humidity'], color='green')
axes[1,0].set_title('相对湿度')
axes[1,0].set_xlabel('日期')
axes[1,0].set_ylabel('%')
axes[1,0].tick_params(axis='x', rotation=45)

# 子图4:气压
axes[1,1].plot(df.index, df['pressure'], color='blue')
axes[1,1].set_title('气压变化')
axes[1,1].set_xlabel('日期')
axes[1,1].set_ylabel('hPa')
axes[1,1].tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:00:35