chap07/kadai4.py

サンプルコードのダウンロード

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4import sys
 5import re
 6import json
 7import argparse
 8import datetime
 9import chardet
10from urllib import request
11
12import numpy as np
13import matplotlib as mpl
14from matplotlib import pyplot as plt
15
16# Open-Meteo
17openmeteo = r'https://api.open-meteo.com/v1/forecast?latitude=35.6785&longitude=139.6823&hourly=temperature_2m,precipitation,windspeed_10m,winddirection_10m&windspeed_unit=ms&timezone=Asia%2FTokyo&past_days=1'
18
19
20def parse_args():
21    parser = argparse.ArgumentParser(description=\
22                                     "Plot weather variables obtained from Open-Meteo "
23                                     "https://open-meteo.com/")
24    parser.add_argument('-s', '--save', type=str, default=None,
25                        help='filename for save')
26    args = parser.parse_args()
27
28    return args.save
29
30
31def get_url_contents(url):
32    response = request.urlopen(url)
33    stream   = response.read()
34    # chardet.detectで文字コードを推測
35    encoding = chardet.detect(stream).get('encoding')
36    return stream.decode(encoding)
37
38
39def plot(contents, variables, save=None):
40    # jsonとして読み込み,時系列データを取り出す
41    obj = json.loads(contents)
42    dat = obj['hourly']
43
44    # 時間
45    time = np.array(dat['time'], np.datetime64)
46    tnow = np.datetime64(datetime.datetime.now())
47
48    # データのプロット
49    n = len(variables)
50
51    fig, axs = plt.subplots(n, 1, figsize=(10, 8))
52    fig.subplots_adjust(left=0.1, bottom=0.05, right=0.95, top=0.95,
53                        wspace=0.2, hspace=0.2)
54
55    for i in range(n):
56        # プロット
57        label = variables[i]['label']
58        y = np.array(dat[variables[i]['name']])
59        m = np.size(y)
60        plt.sca(axs[i])
61        plt.plot(time[0:m], y[0:m])
62
63        # 図の見た目を整形
64        ymin, ymax = axs[i].get_ylim()
65        plt.vlines(tnow, ymin, ymax, colors='r', linestyle='dashed')
66        axs[i].set_xlim(time[0], time[-1])
67        axs[i].set_ylim(ymin, ymax)
68        axs[i].set_ylabel(label)
69        axs[i].grid()
70
71    # 緯度・経度を表示
72    lat = obj['latitude']
73    lon = obj['longitude']
74    plt.suptitle('Latitude = {}, Longitude = {}'.format(lat, lon))
75
76    if save is None:
77        # 表示
78        plt.show()
79    else:
80        # ファイルに保存
81        plt.savefig(save)
82
83
84if __name__ == '__main__':
85    # プロットする変数とラベル
86    variables = [
87        {'name' : 'temperature_2m'   , 'label' : 'Temperature [deg]'},
88        {'name' : 'precipitation'    , 'label' : 'Precipitation [mm]'},
89        {'name' : 'windspeed_10m'    , 'label' : 'Wind speed [m/s]'},
90        {'name' : 'winddirection_10m', 'label' : 'Wind Direction [deg]'},
91    ]
92    save = parse_args()
93    contents = get_url_contents(openmeteo)
94    plot(contents, variables, save)