Pythonのデータ可視化ライブラリであるBokehを使用してヒストグラムを作成する方法について説明します。Bokehは、対話的なプロットを簡単に作成できる強力なツールです。
ヒストグラムの作成
まず、numpyを使用してデータを生成します。ここでは、正規分布に従うランダムなデータを生成します。
import numpy as np
rng = np.random.default_rng()
x = rng.normal(loc=0, scale=1, size=1000)
次に、Bokehのfigureオブジェクトを作成し、その上にヒストグラムをプロットします。
from bokeh.plotting import figure, show
p = figure(width=670, height=400, toolbar_location=None, title="Normal (Gaussian) Distribution")
# Histogram
bins = np.linspace(-3, 3, 40)
hist, edges = np.histogram(x, density=True, bins=bins)
p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="skyblue", line_color="white", legend_label="1000 random samples")
最後に、確率密度関数(PDF)をプロットします。
x = np.linspace(-3.0, 3.0, 100)
pdf = np.exp(-0.5*x**2) / np.sqrt(2.0*np.pi)
p.line(x, pdf, line_width=2, line_color="navy", legend_label="Probability Density Function")
p.y_range.start = 0
p.xaxis.axis_label = "x"
p.yaxis.axis_label = "PDF(x)"
show(p)
以上で、PythonとBokehを使用してヒストグラムを作成する方法についての説明を終わります。この記事がPythonとBokehを使用したデータ可視化の一助となれば幸いです。.