libs.utils.graphutil

libs/utils/graphutil.py

  1"""
  2libs/utils/graphutil.py
  3"""
  4
  5import logging
  6from typing import Any
  7
  8import matplotlib.font_manager as fm
  9import matplotlib.pyplot as plt
 10import pandas as pd
 11from matplotlib import use
 12
 13import libs.global_value as g
 14
 15
 16def setup() -> None:
 17    """グラフ設定初期化"""
 18    pd.options.plotting.backend = g.adapter.conf.plotting_backend
 19    match g.adapter.conf.plotting_backend:
 20        case "plotly":
 21            return
 22        case _:
 23            pass  # 以下に処理をベタ書き
 24
 25    plt.close()
 26    plt.rcdefaults()
 27
 28    use(backend="agg")
 29    mlogger = logging.getLogger("matplotlib")
 30    mlogger.setLevel(logging.WARNING)
 31
 32    # スタイルの適応
 33    if (style := g.cfg.setting.graph_style) not in plt.style.available:
 34        style = "ggplot"
 35    plt.style.use(style)
 36
 37    # フォント再設定
 38    for x in ("family", "serif", "sans-serif", "cursive", "fantasy", "monospace"):
 39        if f"font.{x}" in plt.rcParams:
 40            plt.rcParams[f"font.{x}"] = ""
 41
 42    fm.fontManager.addfont(g.cfg.setting.font_file)
 43    font_prop = fm.FontProperties(fname=g.cfg.setting.font_file)
 44    plt.rcParams["font.family"] = font_prop.get_name()
 45
 46    # グリッド線
 47    if not plt.rcParams["axes.grid"]:
 48        plt.rcParams["axes.grid"] = True
 49        plt.rcParams["grid.alpha"] = 0.3
 50        plt.rcParams["grid.linestyle"] = "--"
 51    plt.rcParams["axes.axisbelow"] = True
 52
 53
 54def gen_xlabel(game_count: int) -> str:
 55    """
 56    X軸ラベル生成
 57
 58    Args:
 59        game_count (int): ゲーム数
 60
 61    Returns:
 62        str: X軸ラベル
 63
 64    """
 65    if g.params.target_count:
 66        xlabel = f"直近 {game_count} ゲーム"
 67    else:
 68        xlabel = f"集計日({game_count} ゲーム)"
 69        match g.params.collection:
 70            case "daily":
 71                xlabel = f"集計日({game_count} ゲーム)"
 72            case "monthly":
 73                xlabel = f"集計月({game_count} ゲーム)"
 74            case "yearly":
 75                xlabel = f"集計年({game_count} ゲーム)"
 76            case "all":
 77                xlabel = f"ゲーム数:{game_count} ゲーム"
 78            case _:
 79                if g.params.search_word:
 80                    xlabel = f"ゲーム数:{game_count} ゲーム"
 81                else:
 82                    xlabel = f"ゲーム終了日時({game_count} ゲーム)"
 83
 84    return xlabel
 85
 86
 87def xticks_parameter(days_list: list[Any]) -> dict[str, Any]:
 88    """
 89    X軸(xticks)に渡すパラメータを生成
 90
 91    Args:
 92        days_list (list[Any]): 日付リスト
 93
 94    Returns:
 95        dict[str, Any]: パラメータ
 96
 97    """
 98    days_list = [str(x).replace("-", "/") for x in days_list]
 99
100    thresholds = [
101        # データ数, 傾き, 位置
102        (3, 0, "center"),
103        (20, -30, "left"),
104        (40, -45, "left"),
105        (80, -60, "left"),
106        (float("inf"), -90, "center"),
107    ]
108
109    for limit, rotation, position in thresholds:
110        if len(days_list) <= limit:
111            break
112
113    return {
114        "ticks": list(range(len(days_list)))[:: int(len(days_list) / 25) + 1],
115        "labels": days_list[:: int(len(days_list) / 25) + 1],
116        "rotation": rotation,
117        "ha": position,
118    }
def setup() -> None:
17def setup() -> None:
18    """グラフ設定初期化"""
19    pd.options.plotting.backend = g.adapter.conf.plotting_backend
20    match g.adapter.conf.plotting_backend:
21        case "plotly":
22            return
23        case _:
24            pass  # 以下に処理をベタ書き
25
26    plt.close()
27    plt.rcdefaults()
28
29    use(backend="agg")
30    mlogger = logging.getLogger("matplotlib")
31    mlogger.setLevel(logging.WARNING)
32
33    # スタイルの適応
34    if (style := g.cfg.setting.graph_style) not in plt.style.available:
35        style = "ggplot"
36    plt.style.use(style)
37
38    # フォント再設定
39    for x in ("family", "serif", "sans-serif", "cursive", "fantasy", "monospace"):
40        if f"font.{x}" in plt.rcParams:
41            plt.rcParams[f"font.{x}"] = ""
42
43    fm.fontManager.addfont(g.cfg.setting.font_file)
44    font_prop = fm.FontProperties(fname=g.cfg.setting.font_file)
45    plt.rcParams["font.family"] = font_prop.get_name()
46
47    # グリッド線
48    if not plt.rcParams["axes.grid"]:
49        plt.rcParams["axes.grid"] = True
50        plt.rcParams["grid.alpha"] = 0.3
51        plt.rcParams["grid.linestyle"] = "--"
52    plt.rcParams["axes.axisbelow"] = True

グラフ設定初期化

def gen_xlabel(game_count: int) -> str:
55def gen_xlabel(game_count: int) -> str:
56    """
57    X軸ラベル生成
58
59    Args:
60        game_count (int): ゲーム数
61
62    Returns:
63        str: X軸ラベル
64
65    """
66    if g.params.target_count:
67        xlabel = f"直近 {game_count} ゲーム"
68    else:
69        xlabel = f"集計日({game_count} ゲーム)"
70        match g.params.collection:
71            case "daily":
72                xlabel = f"集計日({game_count} ゲーム)"
73            case "monthly":
74                xlabel = f"集計月({game_count} ゲーム)"
75            case "yearly":
76                xlabel = f"集計年({game_count} ゲーム)"
77            case "all":
78                xlabel = f"ゲーム数:{game_count} ゲーム"
79            case _:
80                if g.params.search_word:
81                    xlabel = f"ゲーム数:{game_count} ゲーム"
82                else:
83                    xlabel = f"ゲーム終了日時({game_count} ゲーム)"
84
85    return xlabel

X軸ラベル生成

Arguments:
  • game_count (int): ゲーム数
Returns:

str: X軸ラベル

def xticks_parameter(days_list: list[typing.Any]) -> dict[str, typing.Any]:
 88def xticks_parameter(days_list: list[Any]) -> dict[str, Any]:
 89    """
 90    X軸(xticks)に渡すパラメータを生成
 91
 92    Args:
 93        days_list (list[Any]): 日付リスト
 94
 95    Returns:
 96        dict[str, Any]: パラメータ
 97
 98    """
 99    days_list = [str(x).replace("-", "/") for x in days_list]
100
101    thresholds = [
102        # データ数, 傾き, 位置
103        (3, 0, "center"),
104        (20, -30, "left"),
105        (40, -45, "left"),
106        (80, -60, "left"),
107        (float("inf"), -90, "center"),
108    ]
109
110    for limit, rotation, position in thresholds:
111        if len(days_list) <= limit:
112            break
113
114    return {
115        "ticks": list(range(len(days_list)))[:: int(len(days_list) / 25) + 1],
116        "labels": days_list[:: int(len(days_list) / 25) + 1],
117        "rotation": rotation,
118        "ha": position,
119    }

X軸(xticks)に渡すパラメータを生成

Arguments:
  • days_list (list[Any]): 日付リスト
Returns:

dict[str, Any]: パラメータ