分類データを処理する

注釈

本章ではいくつかの例を用いる. Pandas これは,データ操作の一般的なツールであるため,表示が容易である.しかし Pandas ここに表示されるコンテンツを作成する必要はありません。

鉄条.

基本型.

Bokehは基本棒グラフの作成を簡単にし、使用する hbar() そして vbar() 字形方法。以下の例では、以下の一連の簡単な1次因子がある。

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']

Bokeh x軸が絶対であることを通知するために,この要素リストを x_range はいの論点です。 figure()

p = figure(x_range=fruits, ... )

転送因子リストは作成されています FactorRange それがそうです。等価な明示的表現法は:

p = figure(x_range=FactorRange(factors=fruits), ... )

自分で定義したいときは FactorRange 例えば、範囲またはカテゴリパディングを変更することによって。

次に私たちは電話をかけることができます vbar 果物名要素リストを x 座標、条形の高さを top 座標は、任意の座標を選択することもできます width 他の属性を設定することもできます

p.vbar(x=fruits, top=[5, 3, 4, 2, 4, 6], width=0.9)

これら全てを一緒にすると出力が見えます

from bokeh.io import output_file, show
from bokeh.plotting import figure

output_file("bars.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]

p = figure(x_range=fruits, plot_height=250, title="Fruit Counts",
           toolbar_location=None, tools="")

p.vbar(x=fruits, top=counts, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0

show(p)

いつものようにデータを入れることもできます ColumnDataSource として source パラメータが到着する vbar データを直接パラメータとして渡すのではありませんこの点は後の例で説明する.

ソート

Bokehは、与えられた範囲因子の順に棒グラフを表示するため、棒グラフの“順序付け”棒グラフは、その範囲の因子を順序付けすることと同等である。

以下の例では、果物係数は、対応するカウントに従ってインクリメントされ、棒グラフが順序付けされる。

from bokeh.io import output_file, show
from bokeh.plotting import figure

output_file("bar_sorted.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]

# sorting the bars means sorting the range factors
sorted_fruits = sorted(fruits, key=lambda x: counts[fruits.index(x)])

p = figure(x_range=sorted_fruits, plot_height=350, title="Fruit Counts",
           toolbar_location=None, tools="")

p.vbar(x=fruits, top=counts, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0

show(p)

詰め込む.

一般的に、私たちは影のある棒グラフが欲しいかもしれない。これは様々な方法で達成されることができる。1つの方法は,すべての色をあらかじめ提供しておくことである.これはすべてのデータ(各棒グラフの色を含む)を入れることで ColumnDataSource. Then the name of the column containing the colors is passed to vbar as the color (or line_color/fill_color )パラメータ。以下に示す.

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6
from bokeh.plotting import figure

output_file("colormapped_bars.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]

source = ColumnDataSource(data=dict(fruits=fruits, counts=counts, color=Spectral6))

p = figure(x_range=fruits, y_range=(0,9), plot_height=250, title="Fruit Counts",
           toolbar_location=None, tools="")

p.vbar(x='fruits', top='counts', width=0.9, color='color', legend_field="fruits", source=source)

p.xgrid.grid_line_color = None
p.legend.orientation = "horizontal"
p.legend.location = "top_center"

show(p)

テープを着色するもう一つの方法は CategoricalColorMapper これは,ブラウザ内部の棒グラフをカラーマッピングしたものである.機能があります factor_cmap() これは簡単にできます

factor_cmap('fruits', palette=Spectral6, factors=fruits)

これは vbar 前の例の列名と同じである.全てのものを一緒にして同じストーリーを得ることができます

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
from bokeh.transform import factor_cmap

output_file("colormapped_bars.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]

source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))

p = figure(x_range=fruits, plot_height=250, toolbar_location=None, title="Fruit Counts")
p.vbar(x='fruits', top='counts', width=0.9, source=source, legend_field="fruits",
       line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits))

p.xgrid.grid_line_color = None
p.y_range.start = 0
p.y_range.end = 9
p.legend.orientation = "horizontal"
p.legend.location = "top_center"

show(p)

スタック.スタック

棒グラフ上のもう1つの一般的な動作は、ストリップを一緒に積層することである。Bokehはこれを専門的に hbar_stack() そして vbar_stack() 機能する。以下の例は、上の果物データを示しているが、各果物タイプのストリップは、グループ化ではなくスタックされている。

from bokeh.io import output_file, show
from bokeh.plotting import figure

output_file("stacked.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 4, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="")

p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,
             legend_label=years)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"

show(p)

舞台裏では,これらの関数の動作方式は,別個の呼び出しで連続した列をスタックすることであることに注意されたい. vbar あるいは…。 hbar それがそうです。このような動作は、上述した希薄化例と同様である(すなわち、本例のデータは not “整然とした”データ形式で)。

場合によっては、正の値と負の値を同時に有する棒グラフをスタックしたい場合がある。以下の例は、正の値および負の値で分割されたスタック棒グラフを作成する方法を示す。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure

output_file("stacked_split.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]

exports = {'fruits' : fruits,
           '2015'   : [2, 1, 4, 3, 2, 4],
           '2016'   : [5, 3, 4, 2, 4, 6],
           '2017'   : [3, 2, 4, 4, 5, 3]}
imports = {'fruits' : fruits,
           '2015'   : [-1, 0, -1, -3, -2, -1],
           '2016'   : [-2, -1, -3, -1, -2, -2],
           '2017'   : [-1, -2, -1, 0, -2, -2]}

p = figure(y_range=fruits, plot_height=250, x_range=(-16, 16), title="Fruit import/export, by year",
           toolbar_location=None)

p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend_label=["%s exports" % x for x in years])

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend_label=["%s imports" % x for x in years])

p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None

show(p)

ホバリング工具

スタック棒グラフの場合、Bokehは、一般的な場合に非常に有用ないくつかの特別なホバリング変数を提供する。

棒材を積むと、Bokehが自動的に設定されます name 属性はその層のスタック列の値とする.ホバリングツールは $name 特殊変数。

また,HOVER変数 @$name スタック列から各レイヤの値を探すために使用することができる。例えば、ユーザがマウスを名前にホバリングした場合 "US East" そして、そして @$name 相等しい. @{{US East}} それがそうです。

以下の例は、この2つのホバリング変数を示す。

from bokeh.io import output_file, show
from bokeh.plotting import figure

output_file("stacked.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 4, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="hover", tooltips="$name @fruits: @$name")

p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,
             legend_label=years)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"

show(p)

また書き直すことができますのでご注意ください name 手で伝えることで vbar_stack そして hbar_stack それがそうです。この場合には $@name ユーザが提供する列名を検索する.

スタック内の各層に異なるホバリングツールを提供する必要がある場合もある。このような場合には hbar_stack そして vbar_stack 関数は、作成されたすべてのレンダラーのリスト(各スタック1)を返す。これらのツールは、各レイヤのために異なるホバリングツールをカスタマイズするために使用することができる:

renderers = p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=source,
                         legend=[value(x) for x in years], name=years)

for r in renderers:
    year = r.name
    hover = HoverTool(tooltips=[
        ("%s total" % year, "@%s" % year),
        ("index", "$index")
    ], renderers=[r])
    p.add_tools(hover)

組になる.

棒グラフを作成する際には、通常、サブグループに応じてデータを直感的に表示することが望ましい。あなたの用例によると、入れ子クラス座標を使用するか、視覚的に薄くするかの2つの基本的な方法を使用することができます。

入れ子カテゴリ.

描画範囲およびデータの座標が2つまたは3つのレベルを有する場合、Bokehは、グループ間でセパレータを使用する階層記号ラベルを含む軸上の要素を自動的にグループ化する。棒グラフの場合、棒グラフがトップ因子で組み合わされることになる。これは、特に“整列”されたデータから始まる場合、棒グラフグループを実装する最も一般的な方法である可能性がある。

以下の例では、単列座標(各列がフォームの2タプル)を作成することにより、この方法を説明する (fruit, year) それがそうです。したがって,描画は果物タイプごとに軸をグループ化し,呼び出すだけでよい. vbar

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure

output_file("bars.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ['2015', '2016', '2017']

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 3, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

# this creates [ ("Apples", "2015"), ("Apples", "2016"), ("Apples", "2017"), ("Pears", "2015), ... ]
x = [ (fruit, year) for fruit in fruits for year in years ]
counts = sum(zip(data['2015'], data['2016'], data['2017']), ()) # like an hstack

source = ColumnDataSource(data=dict(x=x, counts=counts))

p = figure(x_range=FactorRange(*x), plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="")

p.vbar(x='x', top='counts', width=0.9, source=source)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)

前の例と同様にカラーマッピングを適用することも可能である.上記と同じ果物データの棒グラフを得るには、年を影にした棒グラフを除いて変更してください vbar 使用する関数呼び出し factor_cmapfill_color

p.vbar(x='x', top='counts', width=0.9, source=source, line_color="white",

       # use the palette to colormap based on the the x[1:2] values
       fill_color=factor_cmap('x', palette=palette, factors=years, start=1, end=2))

考えてみてくださいこれらの要素には影響があります (fruit, year) それがそうです。♪the start=1 そして end=2 呼び出している factor_cmap カラーマッピング時に使用するデータ係数の第2の部分を選択する。

視覚が薄くなる.

ストリップをグループ化する別の方法は、ストリップの視覚的シフトを明示的に指定することである。この視覚的なずれは ドッジ. それがそうです。

この場合、私たちのデータは“きちんと”ではない。因子でインデックスされた行を持つ単一のテーブルではありません (fruit, year) 私たちは毎年単独のシリーズを持っています。個々の呼び出しを使ってすべての年のシーケンスを描くことができます vbar しかし各グループの各バーは同じものを持っているからです fruit 要素は棒グラフで視覚的に重なりますこのような重複を防ぐことができます dodge() 関数は、異なる呼び出しごとにオフセットを提供する。 vbar

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.transform import dodge

output_file("dodged_bars.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ['2015', '2016', '2017']

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 3, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

source = ColumnDataSource(data=data)

p = figure(x_range=fruits, y_range=(0, 10), plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="")

p.vbar(x=dodge('fruits', -0.25, range=p.x_range), top='2015', width=0.2, source=source,
       color="#c9d9d3", legend_label="2015")

p.vbar(x=dodge('fruits',  0.0,  range=p.x_range), top='2016', width=0.2, source=source,
       color="#718dbf", legend_label="2016")

p.vbar(x=dodge('fruits',  0.25, range=p.x_range), top='2017', width=0.2, source=source,
       color="#e84d60", legend_label="2017")

p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"

show(p)

スタックとグループ化

スタックおよびパケットのための上述した技術は、スタックされたパケットの棒グラフを作成するために一緒に使用されてもよい。

上記の例を続けると、棒グラフを四半期ごとにパケット化し、各個々の棒グラフを領域ごとにスタックすることができる。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure

output_file("bar_stacked_grouped.html")

factors = [
    ("Q1", "jan"), ("Q1", "feb"), ("Q1", "mar"),
    ("Q2", "apr"), ("Q2", "may"), ("Q2", "jun"),
    ("Q3", "jul"), ("Q3", "aug"), ("Q3", "sep"),
    ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"),

]

regions = ['east', 'west']

source = ColumnDataSource(data=dict(
    x=factors,
    east=[ 5, 5, 6, 5, 5, 4, 5, 6, 7, 8, 6, 9 ],
    west=[ 5, 7, 9, 4, 5, 4, 7, 7, 7, 6, 6, 7 ],
))

p = figure(x_range=FactorRange(*factors), plot_height=250,
           toolbar_location=None, tools="")

p.vbar_stack(regions, x='x', width=0.9, alpha=0.5, color=["blue", "red"], source=source,
             legend_label=regions)

p.y_range.start = 0
p.y_range.end = 18
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None
p.legend.location = "top_center"
p.legend.orientation = "horizontal"

show(p)

混合要素.

2つまたは3つのレベルの階層カテゴリを処理する際には、座標の“より高いレベル”部分のみを使用してフォントを配置することができる。例えば階層的な因子の範囲があれば

factors = [
    ("East", "Sales"), ("East", "Marketing"), ("East", "Dev"),
    ("West", "Sales"), ("West", "Marketing"), ("West", "Dev"),
]

Then it is possible to use just "Sales" and "Marketing" etc. as positions for glyphs. In this case, the position is the center of the entire group. The example below shows bars for each month, grouped by financial quarter, and also adds a line (perhaps for a quarterly average) at the coordinates for Q1, Q2, etc.:

from bokeh.io import output_file, show
from bokeh.models import FactorRange
from bokeh.plotting import figure

output_file("mixed.html")

factors = [
    ("Q1", "jan"), ("Q1", "feb"), ("Q1", "mar"),
    ("Q2", "apr"), ("Q2", "may"), ("Q2", "jun"),
    ("Q3", "jul"), ("Q3", "aug"), ("Q3", "sep"),
    ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"),

]

p = figure(x_range=FactorRange(*factors), plot_height=250,
           toolbar_location=None, tools="")

x = [ 10, 12, 16, 9, 10, 8, 12, 13, 14, 14, 12, 16 ]
p.vbar(x=factors, top=x, width=0.9, alpha=0.5)

p.line(x=["Q1", "Q2", "Q3", "Q4"], y=[12, 9, 13, 14], color="red", line_width=2)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)

この例はまた、線のような他の字形も絶対座標を使用することを示している。

パンダ

Pandas Pythonでテーブルと時系列データをデータ分析するための強力で汎用的なツールです。そうじゃないけど 必要なのは Bokehを通じて、Bokehはあなたがそうする時に生活を容易にしようとしています。

次のグラフはパンダとBokehを用いた場合のいくつかの利点を示しています

  • パンダ GroupBy オブジェクトは初期化に使用できます ColumnDataSource グループ平均またはカウントのような多くの統計的メトリックのための列が自動的に作成されます。

  • GroupBy 対象は直接範囲パラメータとして渡すこともできる figure それがそうです。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral5
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg as df
from bokeh.transform import factor_cmap

output_file("groupby.html")

df.cyl = df.cyl.astype(str)
group = df.groupby('cyl')

source = ColumnDataSource(group)

cyl_cmap = factor_cmap('cyl', palette=Spectral5, factors=sorted(df.cyl.unique()))

p = figure(plot_height=350, x_range=group, title="MPG by # Cylinders",
           toolbar_location=None, tools="")

p.vbar(x='cyl', top='mpg_mean', width=1, source=source,
       line_color=cyl_cmap, fill_color=cyl_cmap)

p.y_range.start = 0
p.xgrid.grid_line_color = None
p.xaxis.axis_label = "some stuff"
p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None

show(p)

なお、上記の例では、列毎にグループ化している 'cyl' CDSにコラムがあります 'cyl' このインデックスに用いる.また、他のグループ化されていない列は、例えば 'mpg' 関連のある列、例えば 'mpg_mean' 加えて,グループごとの平均MPG値を与える.

このような用法は,グループが多層である場合にも適用される.以下の例は、以下のように同じデータをどのようにグループ化するかを示す ('cyl', 'mfr') 階層入れ子軸になります本例では、インデックス列名である 'cyl_mfr' グループ列の名前を接続することで実現される.

from bokeh.io import output_file, show
from bokeh.palettes import Spectral5
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.transform import factor_cmap

output_file("bar_pandas_groupby_nested.html")

df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str)

group = df.groupby(by=['cyl', 'mfr'])

index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1)

p = figure(plot_width=800, plot_height=300, title="Mean MPG by # Cylinders and Manufacturer",
           x_range=group, toolbar_location=None, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])

p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
       line_color="white", fill_color=index_cmap, )

p.y_range.start = 0
p.x_range.range_padding = 0.05
p.xgrid.grid_line_color = None
p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None

show(p)

間期.

これまでに棒グラフを作成するための棒グラフを見てきたが、これは、共通ベースラインから棒グラフを描画することを意味する。ただし、棒字状は、範囲内の任意の間隔を表すために用いられてもよい。

以下の例で使用する hbar 両者を兼ねている. left そして right 提供された属性は、長年のオリンピック短距離銅メダルと金メダル獲得者との間の時間分布を示すために提供される。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.sampledata.sprint import sprint

output_file("sprint.html")

sprint.Year = sprint.Year.astype(str)
group = sprint.groupby('Year')
source = ColumnDataSource(group)

p = figure(y_range=group, x_range=(9.5,12.7), plot_width=400, plot_height=550, toolbar_location=None,
           title="Time Spreads for Sprint Medalists (by Year)")
p.hbar(y="Year", left='Time_min', right='Time_max', height=0.4, source=source)

p.ygrid.grid_line_color = None
p.xaxis.axis_label = "Time (seconds)"
p.outline_line_color = None

show(p)

散乱体.

ジッタの追加

個々の分類カテゴリに複数の分散点を描画する場合,通常点が視覚的に重なり始める場合がある.本例では、Bokehは1つを提供している jitter() 点ごとにランダムに薄くする機能を自動的に適用することができる.

以下の例は、2012年から2016年までのGitHubユーザの各提出時間のハッシュ図を示しており、曜日ごとにグループ化されている。このようなデータの無邪気な図解は、毎日数千個の点が狭い線上で重なることをもたらす。使用することで jitter これらの点を区別して有用なグラフを得ることができます

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.sampledata.commits import data
from bokeh.transform import jitter

output_file("bars.html")

DAYS = ['Sun', 'Sat', 'Fri', 'Thu', 'Wed', 'Tue', 'Mon']

source = ColumnDataSource(data)

p = figure(plot_width=800, plot_height=300, y_range=DAYS, x_axis_type='datetime',
           title="Commits by Time of Day (US/Central) 2012—2016")

p.circle(x='time', y=jitter('day', width=0.6, range=p.y_range),  source=source, alpha=0.3)

p.xaxis[0].formatter.days = ['%Hh']
p.x_range.range_padding = 0
p.ygrid.grid_line_color = None

show(p)

カテゴリーずれ量

次のような操作で分類位置を修正する方法を見てきました ドッジ. そして 震えている. それがそうです。また、分類位置へのオフセットを明示的に提供することができる。これは、例えば、カテゴリの末尾に数値を加えることによって実現される ["Jan", 0.2] カテゴリ“Jan”オフセット値0.2である。階層カテゴリの場合、この値は、既存のリストの末尾、例えば、既存のリストの末尾に追加される。 ["West", "Sales", -0,2] それがそうです。カテゴリリストの末尾の任意の値は、常にオフセットとして解釈される。

例えば、最初の例を最初から使用し、以下のように修正したとする。

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']

offsets = [-0.5, -0.2, 0.0, 0.3, 0.1, 0.3]

# This results in [ ['Apples', -0.5], ['Pears', -0.2], ... ]
x = list(zip(fruits, offsets))

p.vbar(x=x, top=[5, 3, 4, 2, 4, 6], width=0.8)

生成された描画は、対応するオフセット毎に水平オフセットされた棒グラフである。

以下は、異なるカテゴリに関連する時系列を示すより複雑なRidgeグラフの例である。これは,分類オフセットを用いてカテゴリ内の時系列ごとにパッチ座標を指定する.

import colorcet as cc
from numpy import linspace
from scipy.stats.kde import gaussian_kde

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter
from bokeh.plotting import figure
from bokeh.sampledata.perceptions import probly

output_file("ridgeplot.html")

def ridge(category, data, scale=20):
    return list(zip([category]*len(data), scale*data))

cats = list(reversed(probly.keys()))

palette = [cc.rainbow[i*15] for i in range(17)]

x = linspace(-20,110, 500)

source = ColumnDataSource(data=dict(x=x))

p = figure(y_range=cats, plot_width=700, x_range=(-5, 105), toolbar_location=None)

for i, cat in enumerate(reversed(cats)):
    pdf = gaussian_kde(probly[cat])
    y = ridge(cat, pdf(x))
    source.add(y, cat)
    p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

p.outline_line_color = None
p.background_fill_color = "#efefef"

p.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))
p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

p.ygrid.grid_line_color = None
p.xgrid.grid_line_color = "#dddddd"
p.xgrid.ticker = p.xaxis[0].ticker

p.axis.minor_tick_line_color = None
p.axis.major_tick_line_color = None
p.axis.axis_line_color = None

p.y_range.range_padding = 0.12

show(p)

熱図.

上記のすべての場合,定義軸と連続軸を持つ.2つの絶対軸のグラフがある可能性がある.カテゴリごとに定義された矩形に影を付けると最終的には 分類熱図

次の図は、x軸カテゴリが1948年から2016年までの年リストであり、y軸カテゴリが年中の月である図を示している。各矩形は1つに対応している (year, month) この組み合わせは同月とその年の失業率によってカラーマッピングされた。失業率は連続変数なので LinearColorMapper 描画をカラーマッピングするために使用され、右側に視覚マップ例を提供するためにカラーバーにも渡される。

import pandas as pd

from bokeh.io import output_file, show
from bokeh.models import (BasicTicker, ColorBar, ColumnDataSource,
                          LinearColorMapper, PrintfTickFormatter,)
from bokeh.plotting import figure
from bokeh.sampledata.unemployment1948 import data
from bokeh.transform import transform

output_file("unemploymemt.html")

data.Year = data.Year.astype(str)
data = data.set_index('Year')
data.drop('Annual', axis=1, inplace=True)
data.columns.name = 'Month'

# reshape to 1D array or rates with a month and year for each row.
df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()

source = ColumnDataSource(df)

# this is the colormap from the original NYTimes plot
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"]
mapper = LinearColorMapper(palette=colors, low=df.rate.min(), high=df.rate.max())

p = figure(plot_width=800, plot_height=300, title="US Unemployment 1948—2016",
           x_range=list(data.index), y_range=list(reversed(data.columns)),
           toolbar_location=None, tools="", x_axis_location="above")

p.rect(x="Year", y="Month", width=1, height=1, source=source,
       line_color=None, fill_color=transform('rate', mapper))

color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                     ticker=BasicTicker(desired_num_ticks=len(colors)),
                     formatter=PrintfTickFormatter(format="%d%%"))

p.add_layout(color_bar, 'right')

p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "7px"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = 1.0

show(p)

最後の例は,本章の多くの技術:色マッパー,視覚減弱,およびPandas DataFramesを組み合わせている.これらの元素は異なるタイプの“熱マップ”を作成して元素周期表を生成するために使用される。各要素に関する他の情報をチェックすることができるように、ホバリングツールも追加されている。

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.sampledata.periodic_table import elements
from bokeh.transform import dodge, factor_cmap

output_file("periodic.html")

periods = ["I", "II", "III", "IV", "V", "VI", "VII"]
groups = [str(x) for x in range(1, 19)]

df = elements.copy()
df["atomic mass"] = df["atomic mass"].astype(str)
df["group"] = df["group"].astype(str)
df["period"] = [periods[x-1] for x in df.period]
df = df[df.group != "-"]
df = df[df.symbol != "Lr"]
df = df[df.symbol != "Lu"]

cmap = {
    "alkali metal"         : "#a6cee3",
    "alkaline earth metal" : "#1f78b4",
    "metal"                : "#d93b43",
    "halogen"              : "#999d9a",
    "metalloid"            : "#e08d49",
    "noble gas"            : "#eaeaea",
    "nonmetal"             : "#f1d4Af",
    "transition metal"     : "#599d7A",
}

source = ColumnDataSource(df)

p = figure(plot_width=900, plot_height=500, title="Periodic Table (omitting LA and AC Series)",
           x_range=groups, y_range=list(reversed(periods)), toolbar_location=None, tools="hover")

p.rect("group", "period", 0.95, 0.95, source=source, fill_alpha=0.6, legend_field="metal",
       color=factor_cmap('metal', palette=list(cmap.values()), factors=list(cmap.keys())))

text_props = {"source": source, "text_align": "left", "text_baseline": "middle"}

x = dodge("group", -0.4, range=p.x_range)

r = p.text(x=x, y="period", text="symbol", **text_props)
r.glyph.text_font_style="bold"

r = p.text(x=x, y=dodge("period", 0.3, range=p.y_range), text="atomic number", **text_props)
r.glyph.text_font_size="11px"

r = p.text(x=x, y=dodge("period", -0.35, range=p.y_range), text="name", **text_props)
r.glyph.text_font_size="7px"

r = p.text(x=x, y=dodge("period", -0.2, range=p.y_range), text="atomic mass", **text_props)
r.glyph.text_font_size="7px"

p.text(x=["3", "3"], y=["VI", "VII"], text=["LA", "AC"], text_align="center", text_baseline="middle")

p.hover.tooltips = [
    ("Name", "@name"),
    ("Atomic number", "@{atomic number}"),
    ("Atomic mass", "@{atomic mass}"),
    ("Type", "@metal"),
    ("CPK color", "$color[hex, swatch]:CPK"),
    ("Electronic configuration", "@{electronic configuration}"),
]

p.outline_line_color = None
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_standoff = 0
p.legend.orientation = "horizontal"
p.legend.location ="top_center"

show(p)