kma-data-api/plot_weather_with_humidity.py

66 lines
2.3 KiB
Python

import pandas as pd
import matplotlib.pyplot as plt
import os
# 1. 데이터 로드
data_file = 'weather_data_continuous_20260401_20260507.csv'
visible_times_file = 'visible-times.txt'
if not os.path.exists(data_file):
print(f"Error: {data_file} not found.")
exit(1)
df = pd.read_csv(data_file)
df['tm_dt'] = pd.to_datetime(df['tm'], format='%Y%m%d%H%M')
# 2. 표시할 특정 시점 로드
visible_times = []
if os.path.exists(visible_times_file):
with open(visible_times_file, 'r') as f:
for line in f:
t_str = line.strip()
if not t_str: continue
try:
cleaned_time = t_str.replace(':', ' ', 1)
vt = pd.to_datetime(cleaned_time)
visible_times.append(vt)
except:
pass
# 3. 그래프 생성
fig, ax1 = plt.subplots(figsize=(15, 8))
# 축 1: 기온 및 이슬점 (°C)
ax1.set_xlabel('Date')
ax1.set_ylabel('Temperature / Dew Point (°C)', color='tab:red')
ax1.plot(df['tm_dt'], df['ta'], color='tab:red', label='Temperature (ta)', alpha=0.7, linewidth=1.2)
ax1.plot(df['tm_dt'], df['td'], color='tab:orange', label='Dew Point (td)', alpha=0.5, linewidth=1.2)
ax1.tick_params(axis='y', labelcolor='tab:red')
# 축 2: 상대습도 (%)
ax2 = ax1.twinx()
ax2.set_ylabel('Relative Humidity (%)', color='tab:green')
ax2.plot(df['tm_dt'], df['hm'], color='tab:green', label='Humidity (hm)', alpha=0.4, linewidth=1)
ax2.tick_params(axis='y', labelcolor='tab:green')
ax2.set_ylim(0, 105) # 습도는 0~100% 범위
# 4. Visible Times 수직선 표시
for vt in visible_times:
if df['tm_dt'].min() <= vt <= df['tm_dt'].max():
ax1.axvline(x=vt, color='red', linestyle='-', alpha=1.0, linewidth=2, zorder=10)
# 수직선 범례를 위한 더미 라인
ax1.plot([], [], color='red', linestyle='-', label='Target Timestamps', linewidth=2)
# 범례 통합
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines + lines2, labels + labels2, loc='upper right')
plt.title('Weather Time Series (Temperature, Dew Point & Humidity)\nApr 1 - May 7, 2026', fontsize=14)
plt.tight_layout()
# 5. 저장
output_plot = 'weather_timeseries_with_humidity.png'
plt.savefig(output_plot, dpi=150)
print(f"Graph with humidity saved as {output_plot}")