このチュートリアルでは、PythonでBokehライブラリを使用する方法を学びます。matplotlib、numpy、seabornなどは、グラフィックスやビジュアライゼーションのための非常に人気のあるPythonライブラリなので、ほとんどの人が聞いたことがあると思います。Bokehがこれらのライブラリと異なる点は、動的な視覚化が可能であることです。これは最近のブラウザでサポートされており(JSとHTMLを使ってグラフィックを描画するため)、したがって非常に高いレベルのインタラクティブ性を持つWebアプリケーションに使用することができます。
BokehはR言語やScala言語でも利用可能ですが、Pythonの方がより一般的に利用されているようです。
インストール
Pythonを使用してBokenをインストールする最も簡単な方法は、pipパッケージマネージャを使用する方法です。pipがインストールされている場合は、以下のコマンドを実行して、Bokehをダウンロードし、インストールしてください。
$ pip install bokeh
注意:この方法でインストールする場合、numpyがすでにシステムにインストールされている必要があります。
Bokehをインストールするもう1つの方法は、Anacondaディストリビューションを使用する方法です。ターミナルまたはコマンドプロンプトで、以下のコマンドを実行してください。
$ conda install bokeh
この手順が完了したら、以下のコマンドを実行し、インストールが成功したことを確認します。
$ bokeh --version
上記のコマンドが正常に実行され、バージョンが表示されれば、あなたのプログラムでbokehライブラリを使用することができます。
コーディング演習
このパートでは、Bokehライブラリの関数を呼び出して、インタラクティブなビジュアライゼーションを作成する実習を行います。まずは、正方形を作るところから始めてみましょう。
注:この記事中のコード中のコメントは非常に重要です。コードの説明だけでなく、他の意味のある情報を伝えることができます。さらに、コメントアウトされるような「代替」または追加機能があるかもしれませんが、それらの行をアンコメントすることで実行してみることができます。
基本的な図形をプロットする
ここでは、線を引くときに順番に追っていく点の x
と y
の座標を指定します。figure関数は
figureオブジェクトをインスタンス化し、プロットしたいグラフの構成を格納します。ここでは、グラフの X レンジと Y レンジの両方を指定することができ、データの範囲をカバーする 0 から 4 までの値を設定します。そして、
line`メソッドは座標の間を正方形の形で線を描きます。
from bokeh.io import output_file, output_notebook
from bokeh.plotting import figure, show
x = [1, 3, 3, 1, 1]
y = [1, 1, 3, 3, 1]
# Display the output in a separate HTML file
output_file('Square.html', title='Square in Bokeh')
#output_notebook() # Uncomment this line to use iPython notebook
square = figure(title='Square Shape',
plot_height=300, plot_width=300,
x_range=(0, 4), y_range=(0, 4))
# Draw a line using our data
square.line(x, y)
#square.circle(x, y) # Uncomment this line to add a circle mark on each coordinate
# Show plot
show(square)
このコードでは output_file
関数の代わりに output_notebook
関数を使用して、Jupyter ノートブックに結果を表示することもできます。もし、ノートブックを使いたい場合は、この記事中のコードで output_file
関数を output_notebook
に置き換えてください。
上記のスクリプトを実行すると、デフォルトのブラウザの新しいタブに以下のような四角い画面が表示されるはずです。
出力されます。
上の画像では、右側にツール(上からパン、ボックスズーム、ホイールズーム、セーブ、リセット、ヘルプ)が表示されています。これらのツールを使って、グラフを操作することができます。
もう一つ重要なことは、「show」関数を呼び出すたびに、新しい「figure」オブジェクトを作成すると、その新しいfigureを引数として「show」関数を呼び出すとエラーが発生することです。このエラーを解決するには、次のコードを実行します。
from bokeh.plotting import reset_output
reset_output()
reset_outputメソッドは、
show` 関数が現在保持している figure ID をリセットし、新しい figure ID を代入できるようにします。
ここまでは基本的なことですが、今度は1つのグラフに複数の線分やマップの等式を作ることに挑戦してみましょう。最も基本的な例としては、方程式 y = x
, y = x^2
, y = x^3
に対して線を引いてみることでしょう。では、Bokehを使ってそれらを一度に表示するグラフを作る方法を見てみましょう。
from bokeh.plotting import figure, output_file, show
# Declare data for our three lines
x = [1, 2, 3, 4, 5, 6]
x_square = [i**2 for i in x]
x_cube = [i**3 for i in x]
# Declare HTML file as output for when show is called
output_file("Eqs.html")
lines = figure(title='Line Comparisons', x_range=(0, 8), y_range=(0,100),
x_axis_label='X-Axis', y_axis_label='Y-Axis')
lines.line(x, x, legend="y = x", line_width=3) # Line for the equation y=x
lines.square(x, x, legend="y = x", size=10) # Add square boxes on each point on the line
lines.line(x, x_square, legend="y = x^2", line_width=3) #Line for the equation y=x^2
lines.circle(x, x_square, legend="y = x^2", size=10) # Add circles to points since it partially overlaps with y=x
lines.line(x, x_cube, legend="y = x^3", line_width=3) # Line for the equation y=x^3
lines.square(x, x_cube, legend="y = x^2", size=10) # Add square boxes on each point of the line
# Display the graph
show(lines)
出力
さらにいくつかのグラフを描く前に、まずグラフィックをよりインタラクティブに、そして美しくするためのクールなトリックをいくつか学びましょう。そのためにまず、Bokehライブラリが使うさまざまなツールについて、グラフの横(上か右側)に表示されるものとは別に学びます。説明は、以下のコードのコメント欄に記載されています。
# Use the same plot data as above
x = [1, 2, 3, 4, 5, 6]
x_square = [i**2 for i in x]
x_cube = [i**3 for i in x]
#now let's make the necessary imports. Note that, in addition to the imports we made in the previous code, we'll be importing a few other things as well, which will be used to add more options in the 'toolset'.
# Same imports as before
from bokeh.plotting import figure, output_file, show
# New imports to add more interactivity in our figures
# Check out Bokeh's documentation for more tools (these are just two examples)
from bokeh.models import HoverTool, BoxSelectTool
output_file("Eqs.html")
# Add the tools to this list
tool_list = [HoverTool(), BoxSelectTool()]
# Use the tools keyword arg, otherwise the same
lines = figure(title='Line Comparisons', x_range=(0, 8), y_range=(0, 100),
x_axis_label='X-Axis', y_axis_label='Y-Axis', tools=tool_list)
# The rest of the code below is the same as above
lines.line(x, x, legend="y = x", line_width=3)
lines.square(x, x, legend="y = x", size=10)
lines.line(x, x_square, legend="y = x^2", line_width=3)
lines.circle(x, x_square, legend="y = x^2", size=10)
lines.line(x, x_cube, legend="y = x^3", line_width=3)
lines.square(x, x_cube, legend="y = x^2", size=10)
# Display the graph
show(lines)
出力
上の図では、以前から利用可能なツールに追加された2つのオプションが確認できます。また、任意のデータポイントにカーソルを合わせるとその詳細が表示されるようになり、さらに特定のデータポイント群を選択して強調表示することもできるようになりました。
カテゴリーデータをボケで扱う
Bokehライブラリを使って次に学ぶことは、カテゴリーデータの取り扱いです。そのために、まず棒グラフを作ってみます。ここでは、アルゼンチン、ブラジル、スペイン、ポルトガルのワールドカップの優勝回数を表す棒グラフを作ってみましょう。面白そうだろ?では、コードを書いてみましょう。
from bokeh.io import show, output_file
from bokeh. plotting import figure
output_file("cups.html")
# List of teams to be included in the chart. Add or
# remove teams (and their World Cups won below) to
# see how it affects the chart
teams = ['Argentina', 'Brazil', 'Spain', 'Portugal']
# Activity: We experimented with the Hover Tool and the
# Box Select tool in the previous example, try to
# include those tools in this graph
# Number of world cups that the team has won
wc_won = [5, 3, 4, 2]
# Setting toolbar_location=None and tools="" essentially
# hides the toolbar from the graph
barchart = figure(x_range=teams, plot_height=250, title="WC Counts",
toolbar_location=None, tools="")
barchart.vbar(x=teams, top=wc_won, width=0.5)
# Acitivity: Play with the width variable and see what
# happens. In particular, try to set a value above 1 for
# it
barchart.xgrid.grid_line_color = 'red'
barchart.y_range.start = 0
show(barchart)
出力
上のグラフを見て、何か気づきましたか?とてもシンプルで、印象に残らないでしょう?上のコードに少し手を加えて、もう少しカラフルで美しいものにしてみましょう。Bokehには、それを手助けするオプションがたくさんあります。それでは、どんなことができるか見てみましょう。
# Mostly the same code as above, except with a few
# additions to add more color to our currently dry graph
from bokeh.io import show, output_file
from bokeh.plotting import figure
# New imports below
from bokeh.models import ColumnDataSource
# A was added 4 to the end of Spectral because we have 4
# teams. If you had more or less you would have used that
# number instead
from bokeh.palettes import Spectral4
from bokeh.transform import factor_cmap
output_file("cups.html")
teams = ['Argentina', 'Brazil', 'Spain', 'Portugal']
wc_won = [5, 3, 4, 2]
source = ColumnDataSource(data=dict(teams=teams, wc_won=wc_won, color=Spectral4))
barchart = figure(x_range=teams, y_range=(0,8), plot_height=250, title="World Cups Won",
toolbar_location=None, tools="")
barchart.vbar(x='teams', top='wc_won', width=0.5, color='color', legend='teams', source=source)
# Here we change the position of the legend in the graph
# Normally it is displayed as a vertical list on the top
# right. These settings change that to a horizontal list
# instead, and display it at the top center of the graph
barchart.legend.orientation = "horizontal"
barchart.legend.location = "top_center"
show(barchart)
出力してみましょう。
明らかに、新しいグラフは、インタラクティブ性が追加され、以前よりずっと良く見えます。
最後に、今回紹介したのはBokehの機能のほんの一部に過ぎないことをお伝えしておきます。Bokehのドキュメントを参照し、利用可能なサンプルに従って試してみてください。
しかし、ドキュメント以外にも、Pythonでのデータ可視化のような素晴らしいリソースがたくさんあります。ここでは、Bokehのさらに詳細なガイドと、Pythonの他の8つの可視化ライブラリが手に入ります。
結論
まとめると、このチュートリアルではBokehライブラリのPython版について学びました。また、 pip
または anaconda
ディストリビューションを使用してダウンロードおよびインストールする方法を見ました。Bokehライブラリのプログラムを使って、様々なデータ型を使ったインタラクティブでダイナミックなビジュアライゼーションを作成しました。また、matplotlibやSeabornのようなもっと有名な可視化ライブラリがあるにもかかわらず、なぜBokehが必要なのか、実用例を見て学びました。要するに、Bokehは非常に機知に富んでいて、あなたが望むであろうあらゆる種類のインタラクティブな視覚化を行うことができます。