Skip to content

Latest commit

 

History

History
138 lines (104 loc) · 5.46 KB

File metadata and controls

138 lines (104 loc) · 5.46 KB

plot_lib.timeplot

pandas.DataFrame を入力に、matplotlib(pyplot) または plotly で時系列のマルチプロット(複数段のサブプロット・各段での重ね書き)を作成するモジュール。

API

def timeplot(
    df: pd.DataFrame,
    xplot: str,
    yplot: list[str] | list[list[str]],
    plot_type: Literal["pyplot", "plotly"] = "pyplot",
    title: str | None = None,
    ylabel: str | list[str | None] | None = None,
    figsize: tuple[float, float] = (10.0, 3.0),
)

パラメータ

引数 説明
df プロット対象のデータフレーム。
xplot x軸に使うカラム名 (時刻カラムなど)。
yplot y軸カラムの指定。下記「yplot の指定方法」を参照。
plot_type "pyplot" (matplotlib) か "plotly"
title グラフ全体のタイトル。
ylabel 各段のy軸ラベル。文字列1つなら全段共通、リストなら段ごとに指定 (yplot の段数と同じ長さにすること)。
figsize matplotlib使用時の1段あたりの (幅, 高さ)

戻り値

  • plot_type="pyplot"matplotlib.figure.Figure
  • plot_type="plotly"plotly.graph_objects.Figure

呼び出し側で fig.savefig(...) / fig.show() (matplotlib) や fig.write_html(...) / fig.show() (plotly) などを行う。

yplot の指定方法

yplot は「段(サブプロットの行)ごとにまとめて重ね書きしたい列名のリスト」として指定する。

  • フラットなリスト → 1段にすべて重ね書き

    yplot = ["angle_deg", "temperature"]
    # -> 1段のグラフに angle_deg と temperature を重ねて描画
  • 入れ子リスト → 段ごとに分けてプロット (各段はx軸を共有)

    yplot = [
        ["angle_deg"],
        ["angular_velocity_dps", "temperature"],
    ]
    # -> 2段のグラフ。1段目: angle_deg、2段目: angular_velocity_dps と temperature を重ね書き

df に存在しないカラムを指定した場合は KeyError を送出する。

使用例

matplotlib (pyplot)

from plot_lib.timeplot import timeplot

fig = timeplot(
    df,
    xplot="time",
    yplot=[["angle_deg"], ["angular_velocity_dps", "temperature"]],
    plot_type="pyplot",
    title="angle & velocity",
    ylabel=["deg", "dps / degC"],
)
fig.savefig("timeplot.png")

plotly

fig = timeplot(
    df,
    xplot="time",
    yplot=["angle_deg", "temperature"],
    plot_type="plotly",
    title="angle & temperature",
)
fig.write_html("timeplot.html")

デモ実行:

uv run python src/plot_lib/timeplot.py

VS Code / Jupyter でインタラクティブ表示する (別窓ポップアップ)

plot_type="pyplot" はデフォルトの %matplotlib inline だと静止画になる。 ズーム・パンできる別ウィンドウを開くには、標準ライブラリの Tkinter を使う TkAgg バックエンドが手軽 (追加インストール・VS Code側の設定は不要、 Python標準の Tcl/Tk 同梱でそのまま動く)。セルの先頭で一度だけ切り替える:

# セルの先頭で一度だけ
%matplotlib tk

from plot_lib.timeplot import timeplot

fig = timeplot(df, xplot="time", yplot=["angle_deg"], plot_type="pyplot")
fig.show()  # 別ウィンドウが開き、ツールバーでズーム・パンできる
  • timeplot() 自体はバックエンドを意識せず plt.subplots() で Figure を作るだけなので、 %matplotlib tk を有効にした状態で呼び出せば別窓表示になる (コード側の変更は不要)。
  • fig.show() を呼ばないとウィンドウが前面に出てこない場合があるので明示的に呼ぶこと。
  • スクリプトとして uv run python foo.py のように非対話実行する場合、Windows環境では Tcl/Tk 同梱のため追加設定なしで GUI バックエンドが有効になっている。保存だけでよければ fig.savefig(...) のままでよいが、実行時にウィンドウも見たい場合は最後に plt.show() (ウィンドウを閉じるまでスクリプトが終了しないブロッキング呼び出し) を 追加すればよい (sample/demo_kinematics.py がこのパターンの実例)。
  • ノートブック上に画像として埋め込みたい場合は ipympl (%matplotlib widget) という 選択肢もあるが、VS Code側の設定 (jupyter.widgetScriptSources へのCDN許可) が必要で ハマりやすいため、まずは上記の TkAgg 別窓方式を推奨する。
  • plotly 側はもともとブラウザ/ノートブック上でズーム・パン・ホバー表示が可能な インタラクティブな Figure を返す (追加設定不要)。

日本語フォントについて

title / ylabel に日本語を使うと、matplotlib の既定フォント (DejaVu Sans) では文字化け (tofu) する。timeplot は pyplot 使用時に以下の候補から利用可能なフォントを自動検出して matplotlib.rcParams["font.family"] に設定する:

Yu Gothic, Meiryo, MS Gothic, Noto Sans JP, Noto Sans CJK JP, Hiragino Sans

いずれも見つからない環境ではデフォルトフォントのまま動作する (日本語部分は文字化けする可能性がある)。