8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jupyter Notebookでグラフをインタラクティブに操作できるplotlyを使ってみたらめっちゃ便利だった

Last updated at Posted at 2025-12-08

背景

Pythonでグラフを描画するとき、よくmatplotlibを使うと思います。
ただ、x/yの範囲を始め見た目を変えるときや、中身の細かい数字を見たいときに
一々ポチポチコードを実行する必要があり、面倒なことがあります。

Plotlyというライブラリを使うと、Jupyter Notebook上でグリグリ操作できると聞いて、勉強してみました。

元データ準備

私の家のSwitchbotで計測している気温データを使います。

import pandas as pd 
from tqdm.auto import tqdm

date_range = pd.date_range(start='2025-10-01', end='2025-10-31', freq='D')
f_list = []

for d in tqdm(date_range):
    d_str = d.date().isoformat()
    f = pd.read_csv(f'https://ikube.click/202505_switchbot/data/{d_str}.csv')
    f_list.append(f)

df = pd.concat(f_list, ignore_index=True)

df['currentTime'] = pd.to_datetime(df['currentTime'])

サンプルはこんな感じです。deviceIdが複数あり、時間ごとの気温が入っています。

image.png

使い方

参考

matplotlib

# よくあるmatplotlibのプロット
plt.figure(figsize=(10, 5))

for device_id, group in df.groupby('deviceId'):
    plt.plot(group['currentTime'], group['temperature'], label=device_id)

plt.xlabel('Time')
plt.ylabel('Temperature')
plt.title('Temperature per Device')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

seaborn

# seabornだとコード量少なくいい感じになる
plt.figure(figsize=(10, 5))
sns.lineplot(data=df, x='currentTime', y='temperature', hue='deviceId')

plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

どちらも、以下のようなグラフになります。

image.png

本題:plotly

以下のようにimport、初期設定します

import plotly.express as px # こうやってインポートするのが定石らしい

import plotly.io as pio
pio.renderers.default = "vscode" # VSCodeのJupyterNotebookだとこうする
# pio.renderers.default = "notebook_connected"  # JupterLabだとこうするらしい
# pio.renderers.default = "colab"  # GoogleColabだとこうする

折れ線グラフ

fig = px.line(
    df, # データフレームを指定
    x="currentTime",
    y="temperature",
    color="deviceId",
    # markers=True,
    title="Temperature by Device"
)

fig.update_layout(xaxis_title="Time", yaxis_title="Temperature")
fig.show()

image.png

htmlにして保存したもの(Jupyter Notebookで同じものが見えます)

めっちゃ便利・・・!

  • Jupyer Notebook上でマウスを乗せるとデータが表示される
  • 右側の凡例をクリックすると表示する要素を消せる
  • 右上のボタンで拡大・縮小・表示のリセットなどができる
  • 右上のカメラのアイコンでpngでエクスポートできる
    • 拡大・縮小を維持したままエクスポートできる
    • ただし画質はデフォではちょっとイマイチ?

積み上げ棒グラフ

自分がよく使うグラフを勝手に紹介していきます。

# データ準備
df['battery'] = df['battery'].astype(int)

# サンプリング
df_midnight = df[
    (df["currentTime"].dt.hour == 0) &
    (df["currentTime"].dt.minute == 0)
]

df_midnight['day'] = df_midnight['currentTime'].dt.day

# 描画
fig = px.bar(
    df_midnight, 
    x="day", 
    y="battery", 
    color="deviceId", 
    title="total battery by day")
fig.show()

image.png

散布図

fig = px.scatter(
    df, 
    x="temperature", 
    y="humidity", 
    color="deviceId", # 色を分けるカラムを指定
    symbol="deviceId", # マーカーの形を分けるカラムを指定
    hover_data=["currentTime", "battery"], # マウスオーバで表示されるカラム
    title="temp vs humid")
fig.show()

image.png

参考

ドキュメントはこちら

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?