愛媛県感染症情報センターのインフルエンザ患者数をグラフ化

import datetime
import re

import pandas as pd
import requests
from bs4 import BeautifulSoup

import matplotlib.pyplot as plt
import seaborn as sns

sns.set()

import japanize_matplotlib

r = requests.get("https://www.pref.ehime.jp/h25115/kanjyo/topics/influ1920/tb_flu1920.html")

r.raise_for_status()

soup = BeautifulSoup(r.content, "html5lib")

# タイムゾーン
JST = datetime.timezone(datetime.timedelta(hours=+9), "JST")

# 更新時間取得
dt_web = datetime.datetime.strptime(
    r.headers["Last-Modified"], "%a, %d %b %Y %H:%M:%S %Z"
).astimezone(JST)

# 現在
dt_now = datetime.datetime.now(JST)

# 更新チェック
if dt_web > (dt_now - datetime.timedelta(days=1)):

    # 何週目
    text = soup.select_one("#tmp_contents > h2").get_text(strip=True)
    m = re.search(r"令和.{1,2}年(第\d{1,2}週)", text)
    week = m.group(1)

    # 愛媛県感染症情報センター インフルエンザ
    df1 = pd.read_html(
        "https://www.pref.ehime.jp/h25115/kanjyo/topics/influ1920/tb_flu1920.html",
        index_col=[0, 1],
        header=0,
        match="最新週の患者報告数",
    )[0].T

    df1.fillna(0, inplace=True)

    # 定点当たり患者報告数
    influ_point = df1["定点当たり"]

    ax = influ_point.plot.barh(title=f"定点当たり患者報告数({week})", legend=None)

    # 注意報ライン
    ax.axvline(x=10, linestyle="--", color="orange", linewidth=1, label="注意報")

    # 警報ライン
    ax.axvline(x=30, linestyle="--", color="red", linewidth=1, label="警報")

    # グラフを保存
    plt.savefig("01.png", dpi=300, bbox_inches="tight")

    # インフルエンザ型別患者報告数
    influ_count = df1["迅速検査"].copy()
    influ_count.drop("愛媛県", inplace=True)

    ax = influ_count.plot.barh(title=f"インフルエンザ型別患者報告数({week})", stacked=True)

    # 凡例のタイトルを削除
    ax.legend(title=None)

    # グラフを保存
    plt.savefig("02.png", dpi=300, bbox_inches="tight")

    df2 = pd.read_html(
        "https://www.pref.ehime.jp/h25115/kanjyo/topics/influ1920/index1920.html",
        index_col=1,
        header=1,
        match="定点医療機関における保健所別患者報告数",
    )[0]

    df2.drop("Unnamed: 0", axis=1, inplace=True)

    # 患者数のみ抽出
    df_week = df2.iloc[0:6:2, :].fillna(0).astype(float)

    # 週別保健所別患者報告数(定点当たり)
    ax = df_week.T.plot.barh(title="保健所別定点当たり患者報告数(週別)")

    # 注意報ライン
    ax.axvline(x=10, linestyle="--", color="orange", linewidth=1, label="注意報")

    # 警報ライン
    ax.axvline(x=30, linestyle="--", color="red", linewidth=1, label="警報")

    # グラフを保存
    plt.savefig("03.png", dpi=300, bbox_inches="tight")

# 経過日数
elapsed_days = (dt_now - dt_web).days
print(f"最新更新日から{elapsed_days}日経過しています")