環境
- Python 3.12.4
- bokeh 3.6.1
内容
以下のサンプルデータを利用して、散布図をプロットしました。
sample.py
from bokeh.sampledata.degrees import data
from bokeh.plotting import figure, output_file, save, ColumnDataSource
print(f"{len(data)=}")
print(data.dtypes)
x_column = "Agriculture"
y_column = "Architecture"
source = ColumnDataSource(data)
fig = figure(x_axis_label=x_column, y_axis_label=y_column)
fig.scatter(
source=source,
x=x_column,
y=y_column,
)
output_file("sample.html")
save(fig)
$ python sample.py
len(data)=42
Year int64
Agriculture float64
Architecture float64
Art and Performance float64
Biology float64
Business float64
Communications and Journalism float64
Computer Science float64
Education float64
Engineering float64
English float64
Foreign Languages float64
Health Professions float64
Math and Statistics float64
Physical Sciences float64
Psychology float64
Public Administration float64
Social Sciences and History float64
dtype: object
参照している列はAgriculture
とArchitecture
だけですが、HTMLファイルにはColumnDataSource
の全データが出力されます。
sample.html
<script type="application/json" id="f88a2b14-1877-42ea-81ff-fedc7e181d63">
...
["Year",{"type":"ndarray","array":{"type":"bytes","data":"sgcAALMHAAC0BwAAtQcAALYHAAC3BwAAuAcAALkHAAC6BwAAuwcAALwHAAC9BwAAvgcAAL8HAADABwAAwQcAAMIHAADDBwAAxAcAAMUHAADGBwAAxwcAAMgHAADJBwAAygcAAMsHAADMBwAAzQcAAM4HAADPBwAA0AcAANEHAADSBwAA0wcAANQHAADVBwAA1gcAANcHAADYBwAA2QcAANoHAADbBwAA"}
...
</script>
HTMLファイルのサイズを縮小するために、必要最小限のデータのみを含むColumnDataSource
を生成して、HTMLファイルを出力しました。
sample2.py
source = ColumnDataSource(data[[x_column, y_column]])
...
output_file("sample2.html")
ファイルサイズは約半分になりました。
$ ls *.html -l
-rw-r--r-- 1 yuji yuji 16519 Nov 22 02:22 sample.html
-rw-r--r-- 1 yuji yuji 7626 Nov 22 02:30 sample2.html
今回のデータは42件です。データ件数が1000件以上ならば、ファイルサイズ縮小の効果は大きいでしょう。