Bokeh高阶使用笔记V0.1
发布时间:2021-12-03
公开文章
下面是笔者使用过程中遇到一些问题解决方案,仅供参考:
# 工具条
TOOLS="hover,crosshair,pan,wheel_zoom,box_zoom,reset,tap,save,box_select,poly_select,lasso_select"
p=figure(tools=TOOLS) # 创建画布,伪代码
颜色
# HEX颜色,画布1,绘图1
colors2 = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]
# 画布背景颜色
p = figure(title="log axis example", y_axis_type="log",
x_range=(0, 5), y_range=(0.001, 10**22),
background_fill_color="#fafafa")
坐标轴
直角坐标
p = figure(
tools="pan,box_zoom,reset,save",
y_axis_type="log", title="log axis example",
x_axis_label='sections', y_axis_label='particles',
width=700, height=350) #坐标轴的数据格式 linear、log、datetime、mercator\(墨卡托)
from bokeh.models import Range1d,SingleIntervalTicker
xdr=Range1d(start=0,end=10) #早期版本需要预定义
p=figure(x_range=xdr) # x轴范围,新版本可以直接用列表
p.xaxis.ticker = SingleIntervalTicker(interval=5,num_minor_ticks=0) # 刻度间隔步距,间隔起点
from bokeh.models import ColumnDataSource, NumeralTickFormatter, SingleIntervalTicker
p.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=0)
p.yaxis.formatter = NumeralTickFormatter(format='0.0a') # 数据位数
p2.ygrid.band_fill_color = "olive" # 自定义y轴数据间隔颜色
p2.ygrid.band_fill_alpha = 0.1
from bokeh.models import ColumnDataSource, FactorRange
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) # 功能上FactorRange映射较直接采用Range1d维度更多
极坐标
p.arc(x, y, 20, 0.6, 4.1, radius_units="screen", color="#BEAED4", line_width=3) # radius_units="screen" 屏幕像素坐标
时间序列
from bokeh.models import ColumnDataSource, DatetimeAxis
# 设置时间轴
plot.add_layout(DatetimeAxis(), 'below')
plot.add_layout(DatetimeAxis(), 'left')
from bokeh.models import ColumnDataSource, DatetimeAxis, DatetimeTickFormatter
xformatter = DatetimeTickFormatter(months="%b %d %Y")
from time import mktime
min_time = dt.datetime.min.time()
xticker = FixedTicker(ticks=[
mktime(dt.datetime.combine(summer_start, min_time).timetuple()) * 1000,
mktime(dt.datetime.combine(summer_end, min_time).timetuple()) * 1000
])
xaxis = DatetimeAxis(formatter=xformatter, ticker=xticker)
plot.add_layout(xaxis, 'below')
yaxis = DatetimeAxis()
yaxis.formatter.hours = ['%H:%M']
plot.add_layout(yaxis, 'left')
legend = Legend(items=[
LegendItem(label=value('sunset'), renderers=[sunset_line_renderer]),
LegendItem(label=value('sunrise'), renderers=[sunrise_line_renderer]),
])
plot.add_layout(legend)
数据标记
# 机器学习分类颜色、标记自动映射
from bokeh.transform import factor_cmap, factor_mark
p.scatter("petal_length", "sepal_width", source=flowers, legend="species", fill_alpha=0.4, size=12,
marker=factor_mark('species', MARKERS, SPECIES),
color=factor_cmap('species', 'Category10_3', SPECIES))
动态交互
p.legend.click_policy="hide" # 通过点击图例显示、隐藏图形
from bokeh.models import BoxSelectTool, Div
div = Div(text="""
<p>Bokeh中的画布可通过多种布局方式进行显示;</p>
<p>通过配置参数BoxSelectTool,在图中用鼠标选择数据,采用不同方式进行交互。</p>
""") # HTML代码直接在作为一个图层显示,也可以整个HTML文档
p2 = figure(title="selection on mousemove", **opts)
p2.square(x, y, color="olive", size=6, alpha=0.6)
p2.select_one(BoxSelectTool).select_every_mousemove = True # 使用鼠标选择数据点
layout = column(div, # 直接显示html标签
gridplot([[p1, p2], [p3, p4]], toolbar_location="right"),
sizing_mode="scale_width") # sizing_mode 根据窗口宽度缩放图像
# 绘图
show(layout)
from bokeh.io import push_notebook
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# 通过画布的句柄更新数据
plot.title.text = "New Title"
push_notebook(handle=handle)
show(plot)
# 通过画布直接关联不通过图件的数据
# 画布1
s1 = figure(title=None)
s1.circle(x, y0, size=3, color="navy", alpha=0.5)
# 画布2,关联画布1的x,y轴范围
s2 = figure(x_range=s1.x_range, y_range=s1.y_range, title=None)
s2.circle(x, y1, size=3, color="firebrick", alpha=0.5)
# 画布3,关联画布1的x轴范围,仅随着画布1的x轴方向拖动变化
s3 = figure(x_range=s1.x_range, title=None)
s3.circle(x, y2, size=3, color="olive", alpha=0.5)
# 网格
p = gridplot([[s1, s2, s3]], toolbar_location=None, plot_width=250, plot_height=250)
# 控件及JS数据回调(略)
地理位置信息
# 借鉴folium,通过Bokeh与Flask动态交互,或本地保存JPG
# tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', # 高德街道图
tiles='http://webst02.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', # 高德卫星图
# tiles='https://mt.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', # google 卫星图
# tiles='https://mt.google.com/vt/lyrs=h&x={x}&y={y}&z={z}', # google 地图
'''
cb_obj:
const f = cb_obj.value,
const f = cb_obj.range
携带控件对象的数据;
cb_data:
const indices = cb_data.index.indices
cb_data.source
cb_data.geometries
携带特定工具的数据,如鼠标坐标和悬停工具的悬停数据索引;
'''