kma-data-api/plot_weather_data.py

70 lines
2.6 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:
# "2026-04-17: 13:20" 에서 첫 번째 ":" 만 공백으로 변경
# 결과: "2026-04-17 13:20"
cleaned_time = t_str.replace(':', ' ', 1)
vt = pd.to_datetime(cleaned_time)
visible_times.append(vt)
except Exception as e:
print(f"Parsing error for '{t_str}': {e}")
# 3. 그래프 생성
fig, ax1 = plt.subplots(figsize=(15, 8))
# 축 1: 기온 및 이슬점
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.6, linewidth=1)
ax1.plot(df['tm_dt'], df['td'], color='tab:orange', label='Dew Point (td)', alpha=0.4, linewidth=1)
ax1.tick_params(axis='y', labelcolor='tab:red')
# 축 2: 풍속 (twinx)
ax2 = ax1.twinx()
ax2.set_ylabel('Wind Speed (m/s)', color='tab:blue')
ax2.plot(df['tm_dt'], df['ws_10m'], color='tab:blue', label='Wind Speed (ws)', alpha=0.3, linewidth=0.8)
ax2.tick_params(axis='y', labelcolor='tab:blue')
# 4. Visible Times 수직선 표시 (가시성 극대화: 빨간색 실선)
plotted_count = 0
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)
plotted_count += 1
# 수직선 범례를 위한 더미 라인
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 (Apr 1 - May 7, 2026)\nTarget Coordinate: 34.925323N, 127.710838E', fontsize=14)
plt.tight_layout()
# 5. 저장
output_plot = 'weather_timeseries_plot.png'
plt.savefig(output_plot, dpi=150)
print(f"Fixed graph saved as {output_plot}")
print(f"Parsed {len(visible_times)} timestamps, Plotted {plotted_count} lines.")