import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import matplotlib.colors as mcolors

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 数据
months = list(range(1, 13))
temperature = [2.1, 4.5, 9.8, 16.2, 21.5, 25.8, 28.5, 27.9, 23.2, 17.5, 10.8, 4.2]
rainfall = [15, 22, 45, 68, 95, 158, 185, 165, 85, 48, 32, 18]

fig, axes = plt.subplots(2, 2, figsize=(12, 10), dpi=300)

# 子图1：折线图 - 全年气温变化趋势，标注最高和最低气温月份
ax1 = axes[0, 0]
ax1.plot(months, temperature, marker='o', color='tomato', linewidth=2)
max_idx = temperature.index(max(temperature))
min_idx = temperature.index(min(temperature))
ax1.annotate(f'最高 {max(temperature)}°C',
             xy=(months[max_idx], temperature[max_idx]),
             xytext=(months[max_idx] - 2, temperature[max_idx] + 1.5),
             arrowprops=dict(arrowstyle='->'))
ax1.annotate(f'最低 {min(temperature)}°C',
             xy=(months[min_idx], temperature[min_idx]),
             xytext=(months[min_idx] + 1, temperature[min_idx] + 3),
             arrowprops=dict(arrowstyle='->'))
ax1.set_title('全年气温变化趋势')
ax1.set_xlabel('月份')
ax1.set_ylabel('气温 (°C)')
ax1.set_xticks(months)

# 子图2：柱状图 - 每月降雨量，渐变色表示降雨量大小
ax2 = axes[0, 1]
# 根据实际降雨量数据进行颜色映射
norm = mcolors.Normalize(vmin=min(rainfall), vmax=max(rainfall))
colors = plt.cm.Blues(norm(rainfall))

ax2.bar(months, rainfall, color=colors)
ax2.set_title('每月降雨量')
ax2.set_xlabel('月份')
ax2.set_ylabel('降水量 (mm)')
ax2.set_xticks(months)

# 子图3：双Y轴图 - 气温（折线）和降雨量（柱状），添加图例
ax3 = axes[1, 0]
ax3_r = ax3.twinx()
line1, = ax3.plot(months, temperature, color='tomato', marker='o', label='气温')
bar1 = ax3_r.bar(months, rainfall, color='steelblue', alpha=0.5, label='降水量')
ax3.set_title('气温与降水量对比')
ax3.set_xlabel('月份')
ax3.set_ylabel('气温 (°C)')
ax3_r.set_ylabel('降水量 (mm)')
ax3.set_xticks(months)
handles1, labels1 = ax3.get_legend_handles_labels()
handles2, labels2 = ax3_r.get_legend_handles_labels()
ax3.legend(handles1 + handles2, labels1 + labels2, loc='upper left')

# 子图4：散点图 - 气温与降雨量关系，计算并显示相关系数
ax4 = axes[1, 1]
ax4.scatter(temperature, rainfall, color='purple', s=60)
slope, intercept, r_value, p_value, std_err = stats.linregress(temperature, rainfall)
x_line = np.linspace(min(temperature), max(temperature), 100)
y_line = slope * x_line + intercept
ax4.plot(x_line, y_line, color='orange', linestyle='--', label=f'拟合线')
ax4.set_title(f'气温与降水量散点图（相关系数 r = {r_value:.4f}）')
ax4.set_xlabel('气温 (°C)')
ax4.set_ylabel('降水量 (mm)')
ax4.legend()

plt.tight_layout()
plt.savefig('weather_analysis.png', dpi=300)
plt.show()
print("图表已保存为 weather_analysis.png")
