bokehとは
pythonでインタラクティブなグラフが作成できるライブラリです。
折れ線グラフを作成する
# 必要なライブラリをインポート
from bokeh.plotting import figure, output_file, save
from bokeh.models import ColumnDataSource
import pandas as pd
from datetime import datetime
# データを準備
data = {
'date': ['2024-07-01', '2024-07-02', '2024-07-03', '2024-07-04', '2024-07-05'],
'value': [6, 7, 2, 4, 7]
}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
# BokehのColumnDataSourceにデータを変換
source = ColumnDataSource(df)
# 出力ファイルの設定(HTMLファイル)
output_file("timeseries_line_plot.html")
# 図を作成
p = figure(title="Time Series Line Plot Example",
x_axis_label='Date',
y_axis_label='Value',
x_axis_type='datetime',
toolbar_location=None,
background_fill_color="#fafafa")
# 折れ線グラフを追加
p.line('date', 'value', source=source, line_width=2)
# グラフを保存
save(p)
2020年から2021年のグラフの背景を灰色にする
# 必要なライブラリをインポート
from bokeh.plotting import figure, output_file, save
from bokeh.models import ColumnDataSource, BoxAnnotation
import pandas as pd
# データを準備
data = {
'date': ['2024-07-01', '2024-07-02', '2024-07-03', '2024-07-04', '2024-07-05'],
'value': [6, 7, 2, 4, 7]
}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
# BokehのColumnDataSourceにデータを変換
source = ColumnDataSource(df)
# 出力ファイルの設定(HTMLファイル)
output_file("timeseries_line_plot_with_annotation.html")
# 図を作成
p = figure(title="Time Series Line Plot Example",
x_axis_label='Date',
y_axis_label='Value',
x_axis_type='datetime',
toolbar_location=None,
background_fill_color="#fafafa")
# 折れ線グラフを追加
p.line('date', 'value', source=source, line_width=2)
# 特定期間の背景を灰色にする
highlight = BoxAnnotation(left=pd.to_datetime('2024-07-02'),
right=pd.to_datetime('2024-07-04'),
fill_color='gray', fill_alpha=0.3)
p.add_layout(highlight)
# グラフを保存
save(p)
今後について
https://data.nber.org/data/cycles/
こちらのサイトでアメリカのリセッション期間のデータが掲載されていますので株価のグラフをプロットし。リセッション期間の背景をぬりつぶすことでリセッション期間の株価の動きについて分析しようと思います。