0
0

bokehとは

pythonでインタラクティブなグラフが作成できるライブラリです。

折れ線グラフを作成する

スクリーンショット 2024-07-16 5.14.46.png

# 必要なライブラリをインポート
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年のグラフの背景を灰色にする

スクリーンショット 2024-07-16 5.15.59.png

# 必要なライブラリをインポート
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/
こちらのサイトでアメリカのリセッション期間のデータが掲載されていますので株価のグラフをプロットし。リセッション期間の背景をぬりつぶすことでリセッション期間の株価の動きについて分析しようと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0