Bokehを使ってPythonでインタラクティブなグラフを作成:データの動きを楽しもう

まくまく
まくまく
久しぶりのPython記事です。今回はデータ可視化ライブラリBokehの使い方を学んでみようと思います。



Bokehとは

Bokehはインタラクティブなグラフなどを作成できるPythonのデータ可視化ライブラリです。ちょうど仕事でWebアプリっぽいものを作る機会があったので、BokehやHoloviews、Panelなどの使い方をざっと学ぼうと思ってます。

Bokehのインストール

インストールはpipかcondaで。今回はpipで入れてみます。

pip install bokeh

サンプルデータのダウンロード

チュートリアルなどで使うサンプルデータは以下でダウンロードできます。

import bokeh.sampledata
bokeh.sampledata.download()

line chartを書いてみる

from bokeh.plotting import figure, show

# prepare some data
x = [1, 2, 3, 4, 5]
y1 = [6, 7, 2, 4, 5]
y2 = [2, 3, 4, 5, 6]
y3 = [4, 5, 5, 7, 2]

# create a new plot with a title and axis labels
p = figure(title="Multiple line example", x_axis_label="x", y_axis_label="y")

# add multiple renderers
p.line(x, y1, legend_label="Temp.", color="blue", line_width=2)
p.line(x, y2, legend_label="Rate", color="red", line_width=2)
p.line(x, y3, legend_label="Objects", color="green", line_width=2)

# show the results
show(p)




コードを実行するとぐりぐりと動かすことができるラインチャートグラフが作成されました。

組み合わせグラフ

from bokeh.plotting import figure, show, output_file, save

# prepare some data
x = [1, 2, 3, 4, 5]
y1 = [6, 7, 2, 4, 5]
y2 = [2, 3, 4, 5, 6]
y3 = [4, 5, 5, 7, 2]

# create a new plot with a title and axis labels
p = figure(title="Multiple glyphs example", x_axis_label="x", y_axis_label="y", width=500, height=500)

# add multiple renderers
p.line(x, y1, legend_label="Temp.", color="blue", line_width=2)
p.vbar(x=x, top=y2, legend_label="Rate", width=0.5, bottom=0, color="red")
p.circle(x, y3, legend_label="Objects", color="yellow", size=12)

# show the results
show(p)

# specify the output file path
output_file("graph2.html")
# save the plot as HTML
save(p)



ラインチャート、棒グラフ、散布図などを組み合わせることもできるようです。

HTMLファイルの保存方法

show(p)だけでグラフの表示とHTMLファイルの保存を実行されるようですが、以下のように記載することもできるようです。(ちなみに環境はVS Codeです)

from bokeh.plotting import figure, show, output_file, save
~省略~
# specify the output file path
output_file("graph2.html")
# save the plot as HTML
save(p)
created by Rinker
シーアンドアール研究所
タイトルとURLをコピーしました