# リスト6.6.1:リスト-ライク・オブジェクトのデータを渡したグラフ
from bokeh.charts import output_notebook, Bar, show
output_notebook()
p = Bar([1, 2, 3], plot_width=300, plot_height=200)
show(p)
# リスト6.6.2:辞書型のデータを渡したグラフ
data = {"data": [1, 2, 3], "x_label": ["a", "b", "c"]}
p = Bar(data, values="data", label="x_label", plot_width=300, plot_height=200)
show(p)
# リスト6.6.3:DataFrameを渡したグラフ
import os
import pandas as pd
base_url = (
"https://raw.githubusercontent.com/practical-jupyter/sample-data/master/anime/"
)
anime_master_csv = os.path.join(base_url, "anime_master.csv")
df = pd.read_csv(anime_master_csv)
sum_df = df.groupby("type").sum()
p = Bar(
sum_df,
values="members",
ylabel="メンバ数の合計",
plot_width=400,
plot_height=400,
legend=False,
) # 凡例を非表示
show(p)
# リスト6.6.4:indexをX軸としたグラフ
p = Bar(
sum_df.reset_index(),
label="type",
values="members",
ylabel="メンバ数の合計",
plot_width=400,
plot_height=400,
legend=False,
)
show(p)
# リスト6.6.5:Bokehの集約機能を使用したグラフ
p = Bar(
df,
label="type",
values="members",
agg="sum",
ylabel="メンバ数の合計",
plot_width=400,
plot_height=400,
legend=False,
)
show(p)
# リスト6.6.6:グループ化したグラフ
top10_df = pd.read_csv(os.path.join(base_url, "anime_genre_top10.csv"))
p = Bar(
top10_df,
label="genre",
values="members",
group="type",
agg="sum",
ylabel="メンバ数の合計",
plot_width=600,
plot_height=400,
legend="top_right",
) # 凡例の位置
p.legend.background_fill_alpha = 0 # 凡例の背景を透過 (次章参照)
show(p)
# リスト6.6.7:積み上げ棒グラフ
p = Bar(
top10_df.sort_values("type"),
label="genre",
values="members",
stack="type",
agg="sum",
ylabel="メンバ数の合計",
plot_width=600,
plot_height=400,
legend="top_right",
)
p.legend.padding = 0 # 凡例の中の余白を設定 (次章参照)
p.legend.background_fill_alpha = 0 # 凡例の背景を透過 (次章参照)
show(p)
# リスト6.6.8:vbar()メソッドを使用した棒グラフ
from bokeh.plotting import figure
p = figure(plot_width=200, plot_height=200)
p.vbar(x=[1, 2, 3], top=[1, 2, 3], width=0.5)
show(p)
# リスト6.6.9:hbar()メソッドを使用した棒グラフ
p = figure(plot_width=200, plot_height=200)
p.hbar(y=[1, 2, 3], right=[1, 2, 3], height=0.5)
show(p)
# リスト6.6.10:書式を設定した棒グラフ
from bokeh.palettes import d3
# ジャンルをメンバ数で集計
genre = top10_df.groupby("genre")["members"].sum().sort_values()
p = figure(
title="メンバ数が多いジャンルトップ10",
plot_width=400,
plot_height=400,
x_range=(0, genre.max()),
y_range=(-0.5, len(genre) - 0.5),
)
text_x = genre.min() * 0.1 # 注釈のX座標
colors = d3["Category20b"][10][::-1] # カラーパレット(7章で解説)
# 枠、 罫線、 軸をすべて非表示
p.outline_line_color = None
p.grid.visible = False
p.axis.visible = False
for i, g in enumerate(genre):
text = ": ".join((genre.index[i], "{:,}".format(g)))
p.hbar(y=i, left=0, right=g, height=1, color=colors[i])
p.text(
x=text_x,
y=i,
text=[text],
text_color="#ffffff",
text_font_size="10pt",
text_font_style="bold",
text_baseline="middle",
)
show(p)