付録

Bokehライブラリ

Matplotlib vs BokehMatplotlib(静的)画像として出力Bokeh(インタラクティブ)ブラウザで操作可能

Bokehとは

Bokehは、インタラクティブなWebグラフを作成するためのPythonライブラリです。HTMLファイルとして出力でき、ズームやパンなどの操作が可能です。

python
# Bokehのインストール# pip install bokehfrom bokeh.plotting import figure, show, output_notebookfrom bokeh.models import HoverToolimport numpy as np# Colabで使う場合output_notebook()

基本的なグラフ

折れ線グラフ

python
from bokeh.plotting import figure, showimport numpy as npx = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)p = figure(title="sin(x)のグラフ",           x_axis_label="x",           y_axis_label="y",           width=600, height=400)p.line(x, y, line_width=2, color="blue", legend_label="sin(x)")p.line(x, np.cos(x), line_width=2, color="red",       line_dash="dashed", legend_label="cos(x)")p.legend.location = "top_left"show(p)

散布図

python
from bokeh.plotting import figure, showimport numpy as npnp.random.seed(42)x = np.random.randn(200)y = 2 * x + np.random.randn(200)p = figure(title="散布図",           x_axis_label="x", y_axis_label="y",           width=500, height=500)p.circle(x, y, size=8, color="navy", alpha=0.5)show(p)

棒グラフ

python
from bokeh.plotting import figure, showfrom bokeh.models import ColumnDataSourcecategories = ["A", "B", "C", "D", "E"]values = [23, 45, 12, 67, 34]source = ColumnDataSource(data=dict(    categories=categories,    values=values,))p = figure(x_range=categories,           title="棒グラフ",           x_axis_label="カテゴリ", y_axis_label="値",           width=600, height=400)p.vbar(x="categories", top="values", width=0.7, source=source,       color="steelblue", alpha=0.8)show(p)

ホバーツール(マウスオーバーで情報表示)

python
from bokeh.plotting import figure, showfrom bokeh.models import HoverTool, ColumnDataSourceimport numpy as npnp.random.seed(42)x = np.random.randn(100)y = np.random.randn(100)names = [f"点 {i}" for i in range(100)]source = ColumnDataSource(dict(x=x, y=y, name=names))hover = HoverTool(tooltips=[    ("名前", "@name"),    ("x", "@x{0.00}"),    ("y", "@y{0.00}"),])p = figure(title="ホバーツール付き散布図",           tools=[hover, "pan", "zoom_in", "zoom_out", "reset"],           width=600, height=400)p.circle("x", "y", source=source, size=10, color="navy", alpha=0.6)show(p)

HTMLファイルとして保存

python
from bokeh.plotting import figure, output_file, saveimport numpy as npoutput_file("my_chart.html")  # 保存先を指定x = np.linspace(0, 10, 100)p = figure(title="保存されたグラフ", width=600, height=400)p.line(x, np.sin(x), line_width=2)save(p)  # HTMLファイルとして保存

練習: インタラクティブグラフ

基礎

Bokehを使って、y=x2y = x^2 の放物線グラフを作成し、HTMLファイルとして保存してください。