データの立体表現:Bokehを使ったPythonの3D散布図の作り方

まくまく
まくまく
今回はデータ可視化ライブラリBokehの使い方を学びます。通常の散布図を立体的に表現してみようと思います。



Bokehで散布図を作成する

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

# prepare some data
x = [1, 2, 3, 4, 5]
y = [4, 5, 5, 7, 2]

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

# add circle renderer with additional arguments
circle = p.circle(
    x,
    y,
    legend_label="Objects",
    fill_color="red",
    fill_alpha=0.5,
    line_color="blue",
    size=80,
)

# change color of previously created object's glyph
glyph = circle.glyph
glyph.fill_color = "blue"

# show the results
show(p)



公式チュートリアルほぼそのままのグラフです。プロットが大きいのでエクセルの散布図と少しイメージが異なりますが、各点のサイズは「size」を変更して任意の大きさにすることが可能です。

グラフはもちろんインタラクティブなので、上のように移動やズームなどが可能です。

Y軸に応じてプロットサイズを変更

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

# prepare some data
x = [1, 2, 3, 4, 5]
y = [4, 5, 5, 7, 2]

# サークルのサイズを計算する
sizes = [val * 10 for val in y]


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

# add circle renderer with additional arguments
circle = p.circle(
    x,
    y,
    legend_label="Objects",
    fill_color="red",
    fill_alpha=0.5,
    line_color="blue",
    size= sizes,
)

# change color of previously created object's glyph
glyph = circle.glyph
glyph.fill_color = "blue"

# show the results
show(p)



Y軸の値に応じてプロットサイズを変更してみました。見た目のバランス的にY軸の値を10倍したものをsizeに設定しています。

Z軸を追加したグラフ

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

# prepare some data
x = [1, 2, 3, 4, 5]
y = [4, 5, 5, 7, 2]
z = [70,35,19,46,81]

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

# add circle renderer with additional arguments
circle = p.circle(
    x,
    y,
    legend_label="Objects",
    fill_color="red",
    fill_alpha=0.5,
    line_color="blue",
    size= z,
)

# change color of previously created object's glyph
glyph = circle.glyph
glyph.fill_color = "blue"

# show the results
show(p)



新たにZ軸を用意してsizeにはZ軸の値を設定しました。横軸、縦軸に加えて奥行ができるイメージですね。こういった表現は実務でも結構使えそうな感じです。

created by Rinker
シーアンドアール研究所
タイトルとURLをコピーしました