这是一个气象数据分析程序,主要用于分析和可视化气象数据。以下是该文件的主要功能:
1. 数据加载
- 在线数据:尝试从 GitHub 加载气象数据。
- 示例数据:如果无法加载在线数据,程序会自动生成示例数据。
2. 数据分析
- 年度趋势分析:计算并绘制温度、湿度、降水量和风速的年度趋势图。
- 季节性模式分析:分析并绘制温度、湿度、降水量和风速的季节性变化图。
- 相关性分析:计算并绘制气象要素之间的相关性热图。
3. 数据可视化
- 趋势图:使用 Matplotlib 绘制年度趋势图。
- 柱状图:使用 Seaborn 绘制季节性模式柱状图。
- 热图:使用 Seaborn 绘制相关性热图。
4. 报告生成
- 基本统计信息:计算并显示温度、湿度、降水量和风速的基本统计信息。
- 极端天气事件统计:计算并显示高温天数和暴雨天数。
5. 技术细节
- 数据生成:使用 NumPy 生成随机气象数据,包括温度、湿度、降水量和风速。
- 数据处理:使用 Pandas 进行数据分组和聚合计算。
- 可视化:使用 Matplotlib 和 Seaborn 进行数据可视化。
6. 运行流程
1. 程序启动,尝试加载在线数据,如果失败则生成示例数据。
2. 分析年度趋势,绘制趋势图。
3. 分析季节性模式,绘制柱状图。
- 分析气象要素之间的相关性,绘制热图。
5. 生成并显示分析报告。
7. 依赖库
- Pandas:用于数据处理和分析。
- NumPy:用于数值计算和随机数据生成。
- Matplotlib:用于数据可视化。
- Seaborn:用于高级数据可视化。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
class WeatherAnalyzer:
def __init__(self):
"""初始化天气分析器"""
# 设置基本的图表样式
sns.set_theme() # 使用 seaborn 默认主题
sns.set_style("whitegrid", {'font.sans-serif': ['SimHei', 'DejaVu Sans']})
self.df = None
self.load_data()
def load_data(self):
"""加载气象数据"""
try:
# 尝试从在线源加载数据
url = "https://raw.githubusercontent.com/datasets/weather-data/master/weather.csv"
self.df = pd.read_csv(url)
print("在线数据加载成功!")
except:
print("无法从在线源加载数据,尝试加载示例数据...")
# 创建示例数据
self.create_sample_data()
def create_sample_data(self):
"""创建示例气象数据"""
# 创建过去10年的日期范围
dates = pd.date_range(start='2013-01-01', end='2023-12-31', freq='D')
# 生成随机气象数据
np.random.seed(42) # 设置随机种子以保证可重复性
self.df = pd.DataFrame({
'date': dates,
'temperature': np.random.normal(20, 8, len(dates)), # 温度,均值20,标准差8
'humidity': np.random.normal(60, 15, len(dates)), # 湿度,均值60,标准差15
'precipitation': np.random.exponential(2, len(dates)), # 降水量,指数分布
'wind_speed': np.random.normal(10, 3, len(dates)) # 风速,均值10,标准差3
})
# 添加季节信息
self.df['season'] = pd.to_datetime(self.df['date']).dt.month.map({
12: '冬季', 1: '冬季', 2: '冬季',
3: '春季', 4: '春季', 5: '春季',
6: '夏季', 7: '夏季', 8: '夏季',
9: '秋季', 10: '秋季', 11: '秋季'
})
print("示例数据创建成功!")
def analyze_trends(self):
"""分析气象趋势"""
# 计算年度平均值
yearly_avg = self.df.groupby(pd.to_datetime(self.df['date']).dt.year).agg({
'temperature': 'mean',
'humidity': 'mean',
'precipitation': 'sum',
'wind_speed': 'mean'
})
# 绘制年度趋势图
plt.figure(figsize=(15, 10))
# 温度趋势
plt.subplot(2, 2, 1)
plt.plot(yearly_avg.index, yearly_avg['temperature'], marker='o')
plt.title('年平均温度趋势')
plt.xlabel('年份')
plt.ylabel('温度 (°C)')
# 湿度趋势
plt.subplot(2, 2, 2)
plt.plot(yearly_avg.index, yearly_avg['humidity'], marker='o', color='green')
plt.title('年平均湿度趋势')
plt.xlabel('年份')
plt.ylabel('湿度 (%)')
# 降水量趋势
plt.subplot(2, 2, 3)
plt.plot(yearly_avg.index, yearly_avg['precipitation'], marker='o', color='blue')
plt.title('年总降水量趋势')
plt.xlabel('年份')
plt.ylabel('降水量 (mm)')
# 风速趋势
plt.subplot(2, 2, 4)
plt.plot(yearly_avg.index, yearly_avg['wind_speed'], marker='o', color='purple')
plt.title('年平均风速趋势')
plt.xlabel('年份')
plt.ylabel('风速 (m/s)')
plt.tight_layout()
plt.show()
def analyze_seasonal_patterns(self):
"""分析季节性模式"""
# 计算季节平均值
seasonal_avg = self.df.groupby('season').agg({
'temperature': 'mean',
'humidity': 'mean',
'precipitation': 'mean',
'wind_speed': 'mean'
})
# 设置季节顺序
season_order = ['春季', '夏季', '秋季', '冬季']
seasonal_avg = seasonal_avg.reindex(season_order)
# 绘制季节性模式图
plt.figure(figsize=(15, 10))
# 温度的季节性变化
plt.subplot(2, 2, 1)
sns.barplot(x=seasonal_avg.index, y=seasonal_avg['temperature'])
plt.title('季节平均温度')
plt.ylabel('温度 (°C)')
# 湿度的季节性变化
plt.subplot(2, 2, 2)
sns.barplot(x=seasonal_avg.index, y=seasonal_avg['humidity'], color='green')
plt.title('季节平均湿度')
plt.ylabel('湿度 (%)')
# 降水量的季节性变化
plt.subplot(2, 2, 3)
sns.barplot(x=seasonal_avg.index, y=seasonal_avg['precipitation'], color='blue')
plt.title('季节平均降水量')
plt.ylabel('降水量 (mm)')
# 风速的季节性变化
plt.subplot(2, 2, 4)
sns.barplot(x=seasonal_avg.index, y=seasonal_avg['wind_speed'], color='purple')
plt.title('季节平均风速')
plt.ylabel('风速 (m/s)')
plt.tight_layout()
plt.show()
def analyze_correlations(self):
"""分析气象要素之间的相关性"""
# 计算相关系数矩阵
corr_matrix = self.df[['temperature', 'humidity', 'precipitation', 'wind_speed']].corr()
# 绘制相关性热图
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('气象要素相关性分析')
plt.show()
def generate_report(self):
"""生成分析报告"""
# 计算基本统计量
stats = self.df.describe()
print("\n=== 气象数据分析报告 ===")
print("\n基本统计信息:")
print(stats)
# 计算极端天气事件
print("\n极端天气事件统计:")
extreme_temp = len(self.df[self.df['temperature'] > stats['temperature']['75%'] + 1.5 *
(stats['temperature']['75%'] - stats['temperature']['25%'])])
extreme_precip = len(self.df[self.df['precipitation'] > stats['precipitation']['75%'] + 1.5 *
(stats['precipitation']['75%'] - stats['precipitation']['25%'])])
print(f"高温天数: {extreme_temp}")
print(f"暴雨天数: {extreme_precip}")
def main():
print("开始气象数据分析...")
try:
# 创建分析器实例
analyzer = WeatherAnalyzer()
# 分析趋势
print("\n分析年度趋势...")
analyzer.analyze_trends()
# 分析季节性模式
print("\n分析季节性模式...")
analyzer.analyze_seasonal_patterns()
# 分析相关性
print("\n分析气象要素相关性...")
analyzer.analyze_correlations()
# 生成报告
analyzer.generate_report()
except Exception as e:
print(f"分析过程中出现错误: {str(e)}")
if __name__ == "__main__":
main()