書き込みを加える

Bokehにはいくつかの異なるタイプのアノテーションが含まれており,ユーザが彼らの可視化に補足情報を付加することを可能にしている.

職務上の呼び名

Title 注釈は、描画エッジに記述テキストを提示することを可能にする。

使用時 bokeh.plotting あるいは…。 bokeh.Charts 基本見出しを付与する最も速い方法は,テキストを title パラメータが到着する Figure グラフ関数でもあります

from bokeh.plotting import figure, output_file, show

p = figure(title="Basic Title", plot_width=300, plot_height=300)
p.circle([1,2], [3,4])

output_file("title.html")

show(p)

デフォルトのタイトルは、通常、描画の上部に位置し、左に整列される。しかしデフォルトのタイトルが描画のどちらに現れるかは title_location パラメータ:

from bokeh.plotting import figure, output_file, show

p = figure(title="Left Title", title_location="left",
           plot_width=300, plot_height=300)
p.circle([1,2], [3,4])

output_file("title.html")

show(p)

デフォルト値. Title 通過可能である. Plot.title 財産です。フォント、枠、背景、その他のコンテンツの視覚的属性は直接 .title それがそうです。以下は、以下のコマンドを用いてフォントおよび背景属性、タイトルテキストおよびタイトル整列方式を設定する例である .title

from bokeh.plotting import figure, output_file, show

p = figure(plot_width=300, plot_height=300)
p.circle([1,2], [3,4])

# configure visual properties on a plot's title attribute
p.title.text = "Title With Options"
p.title.align = "right"
p.title.text_color = "orange"
p.title.text_font_size = "25px"
p.title.background_fill_color = "#aaaaee"

output_file("title.html")

show(p)

アライメント方式はテキスト方向に測定されていることに注意されたい。たとえば,描画の左側のタイトルに対して,“Left”は下に位置する.

デフォルトタイトルに加えて、他のものを作成して追加することもできます Title オブジェクトから描画まで、ご利用ください add_layout ブロック方法:

from bokeh.models import Title
from bokeh.plotting import figure, output_file, show

p = figure(title="Left Title", title_location="left",
           plot_width=300, plot_height=300)
p.circle([1,2], [3,4])

# add extra titles with add_layout(...)
p.add_layout(Title(text="Bottom Centered Title", align="center"), "below")

output_file("title.html")

show(p)

タイトルと粘性ツールバーが同じ側に配置されている場合、同じ空間を占める。

from bokeh.plotting import figure, output_file, show

p = figure(title="Top Title with Toolbar", toolbar_location="above",
           plot_width=600, plot_height=300)
p.circle([1,2], [3,4])

output_file("title.html")

show(p)

印刷サイズが十分大きい場合には、よりコンパクトな印刷を生成することができる。しかし、印刷サイズが十分でない場合には、タイトルやツールバーが不要な方法で視覚的に重なる可能性がある。

伝説

作成することができます Legend 描画作成時にフォントメソッドにインスタンスパラメータを指定することで,容易にアノテーションを付加することができる.

基本図例ラベル

字形に簡単な明示的なラベルを提供する場合は、 legend_label キーワードパラメータ:

p.circle('x', 'y', legend_label="some label")

同じラベルが複数のフォントに指定されている場合、それらは、そのラベルを有する単一のインスタンス項にすべてマージされる。

import numpy as np

from bokeh.plotting import figure, output_file, show

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

output_file("legend.html")

p = figure()

p.circle(x, y, legend_label="sin(x)")
p.line(x, y, legend_label="sin(x)")

p.line(x, 2*y, legend_label="2*sin(x)",
       line_dash=[4, 4], line_color="orange", line_width=2)

p.square(x, 3*y, legend_label="3*sin(x)", fill_color=None, line_color="green")
p.line(x, 3*y, legend_label="3*sin(x)", line_color="green")

show(p)

自動グループ化(Python)

複数のインスタンス項目は、一般に、データソース列内の値をグループ化することによって生成されることが望ましい。Bokehは legend_group 字形メソッドのキーワードパラメータ:

p.circle('x', 'y', legend_group="colname", source=source)

この方法を使用すると、Pythonですぐにパケットが実行され、後続のPythonコードが各インスタンス項目を表示することができます。 Legend.items 財産です。必要であれば、これらの項目を再配置したり修正したりすることができる。

from bokeh.io import show
from bokeh.models import ColumnDataSource
from bokeh.palettes import RdBu3
from bokeh.plotting import figure

c1 = RdBu3[2] # red
c2 = RdBu3[0] # blue
source = ColumnDataSource(dict(
    x=[1, 2, 3, 4, 5, 6],
    y=[2, 1, 2, 1, 2, 1],
    color=[c1, c2, c1, c2, c1, c2],
    label=['hi', 'lo', 'hi', 'lo', 'hi', 'lo']
))

p = figure(x_range=(0, 7), y_range=(0, 3), plot_height=300, tools='save')

# legend field matches the column in the source
p.circle( x='x', y='y', radius=0.5, color='color', legend_group='label', source=source)

show(p)

注釈

この機能をご利用になるには、ご利用ください source 論弁. また提供しなければなりません 字形メソッドに追加します。また,このときグループ化する列はすでにデータソースに存在しなければならない.

自動グループ化(ブラウザ)

ブラウザ内のJavaScript側を指定してグループ化することも可能である.これは、例えば、パケットがJavaScript側でのみ計算された列上で発生すべきである場合に理想的である可能性がある。

p.circle('x', 'y', legend_field="colname", source=source)

本例では、Pythonコードは以下の動作を実行します。 not 表示中の複数の項目 Legend.items それがそうです。逆に,ブラウザで実行するグループを示すのは1つのみである.

from bokeh.io import show
from bokeh.models import ColumnDataSource
from bokeh.palettes import RdBu3
from bokeh.plotting import figure

c1 = RdBu3[2] # red
c2 = RdBu3[0] # blue
source = ColumnDataSource(dict(
    x=[1, 2, 3, 4, 5, 6],
    y=[2, 1, 2, 1, 2, 1],
    color=[c1, c2, c1, c2, c1, c2],
    label=['hi', 'lo', 'hi', 'lo', 'hi', 'lo']
))

p = figure(x_range=(0, 7), y_range=(0, 3), plot_height=300, tools='save')

# legend field matches the column in the source
p.circle( x='x', y='y', radius=0.5, color='color', legend_field='label', source=source)

show(p)

手動図例

インスタンスパラメータを指定せずに手動で構築することも可能である. Legend 手作りです。この方面の例については,参照されたい examples/models/file/legends.py

明示的索引

その他の場合は,明示的にBokehに伝える. ColumnDataSource 図の例項を作成する際に使用すべきである.特に、複数の字形の複数の図面項目を描画する場合、例えば、 MultiLine あるいは…。 Patches それがそうです。これは1つを指定することで index 図の例項については,以下のようになる.

from bokeh.models import Legend, LegendItem
from bokeh.plotting import figure, show

p = figure()
r = p.multi_line([[1,2,3], [1,2,3]], [[1,3,2], [3,4,3]],
                 color=["orange", "red"], line_width=4)

legend = Legend(items=[
    LegendItem(label="orange", renderers=[r], index=0),
    LegendItem(label="red", renderers=[r], index=1),
])
p.add_layout(legend)

show(p)

相互作用図例

インスタンスをインタラクティブに構成することも可能であり,インスタンスエントリをクリックしたりクリックしたりすることで対応する字形の視認性に影響を与える.ご参照ください 相互作用図例 より多くの情報および例については、“ユーザーガイド”の部分を参照してください。

注釈

相互作用図例 機能は現在,最初の“字形別”パターンの図例に適用されている.自動グループ化される列を指定することによって作成される図の例は、インタラクション機能をサポートしていない。

色条.

A ColorBar 使用できる ColorMapper インスタンスは、パレットを含む。描画上および描画外のカラーバーを同時にサポートすることができる ColorBar ストーリーの中に行く。

注釈

この例は,オープンソースのNumPyライブラリに依存してプレゼンテーションデータを生成する.

import numpy as np

from bokeh.models import ColorBar, LogColorMapper, LogTicker
from bokeh.plotting import figure, output_file, show

output_file('color_bar.html')

def normal2d(X, Y, sigx=1.0, sigy=1.0, mux=0.0, muy=0.0):
    z = (X-mux)**2 / sigx**2 + (Y-muy)**2 / sigy**2
    return np.exp(-z/2) / (2 * np.pi * sigx * sigy)

X, Y = np.mgrid[-3:3:100j, -2:2:100j]
Z = normal2d(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1*normal2d(X, Y, 1.0, 1.0)
image = Z * 1e6

color_mapper = LogColorMapper(palette="Viridis256", low=1, high=1e7)

plot = figure(x_range=(0,1), y_range=(0,1), toolbar_location=None)
plot.image(image=[image], color_mapper=color_mapper,
           dh=[1.0], dw=[1.0], x=[0], y=[0])

color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
                     label_standoff=12, border_line_color=None, location=(0,0))

plot.add_layout(color_bar, 'right')

show(plot)

矢.矢

Arrow 注釈は、インジケータおよびラベル注釈を接続するために使用されてもよく、または印刷領域をハイライト表示するためにのみ使用されてもよい。矢印は複合書き込みですこれは start そして end 属性自体は他のものである ArrowHead 注釈する。デフォルトの場合、 Arrow 書き込みは一方的である. end 設定は OpenHead -タイプの矢印(開背楔形パターン)および start 属性は、 None それがそうです。両面矢印は2つ設定することができます start そして end 適切な属性 ArrowHead サブクラスインスタンス.

矢印は、矢印軸の色および外観を設定するための標準線特性を有する。

my_arrow.line_color = "blue"
my_arrow.line_alpha = 0.6

矢印はまた、追加の非デフォルトxまたはy範囲を参照するように構成されてもよい。 x_range そして y_range 属性とその方法は 2軸. それがそうです。

また,中のどの矢印オブジェクトも start あるいは…。 end Vbl.ある size 属性は矢印の大きさや,線とフィラー属性を制御する.線特性は矢印の輪郭を制御し,充填特性は矢印の内部を制御する(適用すれば).

from bokeh.models import Arrow, NormalHead, OpenHead, VeeHead
from bokeh.plotting import figure, output_file, show

output_file("arrow.html", title="arrow.py example")

p = figure(plot_width=600, plot_height=600)

p.circle(x=[0, 1, 0.5], y=[0, 0, 0.7], radius=0.1,
         color=["navy", "yellow", "red"], fill_alpha=0.1)

p.add_layout(Arrow(end=OpenHead(line_color="firebrick", line_width=4),
                   x_start=0, y_start=0, x_end=1, y_end=0))

p.add_layout(Arrow(end=NormalHead(fill_color="orange"),
                   x_start=1, y_start=0, x_end=0.5, y_end=0.7))

p.add_layout(Arrow(end=VeeHead(size=35), line_color="red",
                   x_start=0.5, y_start=0.7, x_end=0, y_end=0))

show(p)

バンド.バンド

A Band データまたは画面座標に位置する次元リンクの“ストライプ”が作成される。帯域注釈の一般的な用途の1つは、一連の測定に関連する不確実性を示すことである。

import numpy as np
import pandas as pd

from bokeh.models import Band, ColumnDataSource
from bokeh.plotting import figure, output_file, show

output_file("band.html", title="band.py example")

# Create some random data
x = np.random.random(2500) * 140 - 20
y = np.random.normal(size=2500) * 2 + 5

df = pd.DataFrame(data=dict(x=x, y=y)).sort_values(by="x")

sem = lambda x: x.std() / np.sqrt(x.size)
df2 = df.y.rolling(window=100).agg({"y_mean": np.mean, "y_std": np.std, "y_sem": sem})
df2 = df2.fillna(method='bfill')

df = pd.concat([df, df2], axis=1)
df['lower'] = df.y_mean - df.y_std
df['upper'] = df.y_mean + df.y_std

source = ColumnDataSource(df.reset_index())

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
p = figure(tools=TOOLS)

p.scatter(x='x', y='y', line_color=None, fill_alpha=0.3, size=5, source=source)

band = Band(base='x', lower='lower', upper='upper', source=source, level='underlay',
            fill_alpha=1.0, line_width=1, line_color='black')
p.add_layout(band)

p.title.text = "Rolling Standard Deviation"
p.xgrid[0].grid_line_color=None
p.ygrid[0].grid_line_alpha=0.5
p.xaxis.axis_label = 'X'
p.yaxis.axis_label = 'Y'

show(p)

ブロック注釈.

A BoxAnnotation 特定の描画領域を強調するために、データまたは画面座標にリンクすることができる。デフォルトの場合、ボックス注釈サイズ(例えば、 left あるいは…。 top )注釈を描画領域のエッジに拡張する。

from bokeh.models import BoxAnnotation
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.glucose import data

output_file("box_annotation.html", title="box_annotation.py example")

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

#reduce data size
data = data.loc['2010-10-06':'2010-10-13']

p = figure(x_axis_type="datetime", tools=TOOLS)

p.line(data.index.to_series(), data['glucose'], line_color="gray", line_width=1, legend_label="glucose")

low_box = BoxAnnotation(top=80, fill_alpha=0.1, fill_color='red')
mid_box = BoxAnnotation(bottom=80, top=180, fill_alpha=0.1, fill_color='green')
high_box = BoxAnnotation(bottom=180, fill_alpha=0.1, fill_color='red')

p.add_layout(low_box)
p.add_layout(mid_box)
p.add_layout(high_box)

p.title.text = "Glucose Range"
p.xgrid[0].grid_line_color=None
p.ygrid[0].grid_line_alpha=0.5
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Value'

show(p)

ラベル

ラベルは、注釈フォントまたは印刷領域に使用可能なテキスト要素である。

To create a single text label, use the Label annotation. This annotation is configured with a text property containing the text to be displayed, as well as x and y properties to set the position (in screen or data space units). Additionally, a render mode "canvas" or "css" may be specified. Finally, labels have text, border_line, and background_fill properties. These control the visual appearance of the text, as well as the border and background of the bounding box for the text:

Label(x=70, y=70, x_units='screen', text='Some Stuff', render_mode='css',
      border_line_color='black', border_line_alpha=1.0,
      background_fill_color='white', background_fill_alpha=1.0)

一度に複数のラベルを作成する場合(別の既存の字形を簡単に書き込むためかもしれません)、ご利用ください LabelSet データソースが構成された書き込みであって、 text そして x そして y 位置は列名の形で与えられる. LabelSet 対象はまだ持っていてもいい x_offset そして y_offset これは,スクリーン空間単位でタグ位置のずれ量を指定する. x そして y それがそうです。最後に、ご利用いただけます level 属性は,タグを他のレンダラの上方または下に置く:

LabelSet(x='x', y='y', text='names', level='glyph',
         x_offset=5, y_offset=5, source=source)

以下の例は、両者の使い方を説明する。

from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d
from bokeh.plotting import figure, output_file, show

output_file("label.html", title="label.py example")

source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
                                    weight=[165, 189, 220, 141, 260, 174],
                                    names=['Mark', 'Amir', 'Matt', 'Greg',
                                           'Owen', 'Juan']))

p = figure(title='Dist. of 10th Grade Students at Lee High',
           x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'

labels = LabelSet(x='weight', y='height', text='names', level='glyph',
              x_offset=5, y_offset=5, source=source, render_mode='canvas')

citation = Label(x=70, y=70, x_units='screen', y_units='screen',
                 text='Collected by Luke C. 2016-04-01', render_mode='css',
                 border_line_color='black', border_line_alpha=1.0,
                 background_fill_color='white', background_fill_alpha=1.0)

p.add_layout(labels)
p.add_layout(citation)

show(p)

斜面.坂

Slope アノテーションは,描画領域のエッジまで傾斜して延びることができる線である.

import numpy as np

from bokeh.models import Slope
from bokeh.plotting import figure, output_file, show

output_file("slope.html", title="slope.py example")

# linear equation parameters
gradient = 2
y_intercept = 10

# create random data
xpts = np.arange(0, 20)
ypts = gradient * xpts + y_intercept + np.random.normal(0, 4, 20)

p = figure(plot_width=450, plot_height=450, y_range=(0, 1.1 * max(ypts)))

p.circle(xpts, ypts, size=5, color="skyblue")

slope = Slope(gradient=gradient, y_intercept=y_intercept,
              line_color='orange', line_dash='dashed', line_width=3.5)

p.add_layout(slope)

p.yaxis.axis_label = 'y'
p.xaxis.axis_label = 'x'

show(p)

スパン.スパン

Span 注釈は、単一のサイズ(幅または高さ)を有し、描画領域の縁まで延在する線である。

import time
from datetime import datetime as dt

from bokeh.models import Span
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.daylight import daylight_warsaw_2013

output_file("span.html", title="span.py example")

p = figure(x_axis_type="datetime", y_axis_type="datetime")

p.line(daylight_warsaw_2013.Date, daylight_warsaw_2013.Sunset,
       line_dash='solid', line_width=2, legend_label="Sunset")
p.line(daylight_warsaw_2013.Date, daylight_warsaw_2013.Sunrise,
       line_dash='dotted', line_width=2, legend_label="Sunrise")

start_date = time.mktime(dt(2013, 3, 31, 2, 0, 0).timetuple())*1000
daylight_savings_start = Span(location=start_date,
                              dimension='height', line_color='green',
                              line_dash='dashed', line_width=3)
p.add_layout(daylight_savings_start)

end_date = time.mktime(dt(2013, 10, 27, 3, 0, 0).timetuple())*1000
daylight_savings_end = Span(location=end_date,
                            dimension='height', line_color='red',
                            line_dash='dashed', line_width=3)
p.add_layout(daylight_savings_end)

p.title.text = "2013 Sunrise and Sunset times in Warsaw"
p.yaxis.axis_label = 'Time of Day'

show(p)

ひげ.

A Whisker データまたは画面座標に位置する次元リンクの“茎”が作成されます。一点測定の誤差または不確実度がひげ注釈の一般的な用途であることを指摘する。

from bokeh.models import ColumnDataSource, Whisker
from bokeh.plotting import figure, show
from bokeh.sampledata.autompg import autompg as df

colors = ["red", "olive", "darkred", "goldenrod", "skyblue", "orange", "salmon"]

p = figure(plot_width=600, plot_height=300, title="Years vs mpg with Quartile Ranges")

base, lower, upper = [], [], []

for i, year in enumerate(list(df.yr.unique())):
    year_mpgs = df[df['yr'] == year]['mpg']
    mpgs_mean = year_mpgs.mean()
    mpgs_std = year_mpgs.std()
    lower.append(mpgs_mean - mpgs_std)
    upper.append(mpgs_mean + mpgs_std)
    base.append(year)

source_error = ColumnDataSource(data=dict(base=base, lower=lower, upper=upper))

p.add_layout(
    Whisker(source=source_error, base="base", upper="upper", lower="lower")
)

for i, year in enumerate(list(df.yr.unique())):
    y = df[df['yr'] == year]['mpg']
    color = colors[i % len(colors)]
    p.circle(x=year, y=y, color=color)

show(p)