Bokeh-Web交互

2020年06月29日 9点热度 0人点赞 0条评论
# 导入库
from bokeh.plotting import figure, output_notebook, show
output_notebook()  # 在notebook中显示
plot = figure()
plot.circle([1,2], [3,4])
show(plot)

输出为HTML文件

from bokeh.plotting import output_file
output_file("my plot.html", title="my plot html example")

输出为Html源码

from bokeh.resources import CDN
from bokeh.embed import file_html
html = file_html(plot, CDN, "my plot")
html
html源码内容省略。。。。。
from IPython.display import HTML
HTML(html) # jupyter中嵌入显示
with open("my plot2.html", "w", encoding='utf-8') as f:
    f.write(html)# 保存为html文件

输出为HTML组件

from bokeh.embed import components
plot = figure()
plot.circle([1,2], [3,4])
script, div = components(plot)
print(div )
<div class="bk-root" id="3440c0bf-8f21-4474-8265-a8b8f38ac142" data-root-id="2797"></div>
from bokeh.resources import CDN
from bokeh.plotting import figure
from bokeh.embed import autoload_static
plot = figure()
plot.circle([1,2], [3,4])
js, tag = autoload_static(plot, CDN, "my_plot.js")  #返回js,将其保存,进而在视图模板中通过js文件进行调用

通过web模板显示

import pandas as pd
from bokeh.plotting import figure
from bokeh.sampledata.stocks import AAPL
df = pd.DataFrame(AAPL)
df['date'] = pd.to_datetime(df['date'])
import jinja2  # Flask页面参数传递库
from bokeh.embed import components
# 网页静态模板
template = """
<!DOCTYPE html>
<html lang="en-US">
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css" type="text/css" />   
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.js"></script>
<body>

    <h1>Hello Bokeh!</h1>

    <p> Below is a simple plot of stock closing prices </p>


     {0}
     {1}

</body>

</html>
"""
p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.line(df['date'], df['close'], color='navy', alpha=0.5)
script, div = components(p)  # 输出组件
html = template.format(script,div)
# 传递组件到静态模板显示图像
from IPython.display import HTML
HTML(html)

Hello Bokeh!

Below is a simple plot of stock closing prices

import pandas as pd
from bokeh.plotting import figure
from bokeh.sampledata.stocks import AAPL
df = pd.DataFrame(AAPL)
df['date'] = pd.to_datetime(df['date'])
import jinja2  # Flask页面参数传递库
from bokeh.embed import components
# jinja2网页静态模板
template = jinja2.Template("""
<!DOCTYPE html>
<html lang="en-US">
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css" type="text/css" />   
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.js"></script>
<body>

    <h1>Hello Bokeh!</h1>

    <p> Below is a simple plot of stock closing prices </p>

    {{ script }}

    {{ div }}

</body>

</html>
""")
p = figure(plot_width=800, plot_height=250, x_axis_type="datetime")
p.line(df['date'], df['close'], color='navy', alpha=0.5)
script, div = components(p)  # 输出组件
# 传递组件到静态模板显示图像
from IPython.display import HTML
HTML(template.render(script=script, div=div))

Hello Bokeh!

Below is a simple plot of stock closing prices

# 动态交互
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.embed import components
# 数据
x = [x*0.005 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
# 画布
plot = figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# 回调函数
callback = CustomJS(args=dict(source=source), code="""
    var data = source.data;
    var f = cb_obj.value
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = Math.pow(x[i], f)
    }
    source.change.emit();
""")
# 滑动条
slider = Slider(start=0.1, end=4, value=1, step=.1, title="power")
slider.js_on_change('value', callback)
# 图层,列表显示
layout = column(slider, plot)
# show(layout)  # 直接用Notebook显示
script, div = components(layout)
template2="""
<!DOCTYPE html>
<html lang="en-US">

        <link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css" type="text/css" />
        <link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css" type="text/css" />   
        <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.js"></script>
        <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.js"></script>

<body>

    <h1>Hello Bokeh!</h1>   

    {0}{1}

</body>

</html>
""".format(script,div)
from IPython.display import HTML
HTML(template2) # 用内置HTML函数显示

Hello Bokeh!

from bokeh.resources import CDN
from bokeh.embed import file_html
html = file_html(layout, CDN, "my plot")
from IPython.display import HTML
HTML(html) 

Bokeh Flask

详见文档

Bokeh sever

# 将该示例代保存为sliders.py
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure
# 数据
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
# 画布
plot = figure(plot_height=400, plot_width=400, title="my sine wave",
              tools="crosshair,pan,reset,save,wheel_zoom",
              x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])
# 绘图
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# 控件
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1)
phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
# 回调
def update_title(attrname, old, new):
    plot.title.text = text.value
text.on_change('value', update_title)
def update_data(attrname, old, new):
    # 获取滑块当前数据
    a = amplitude.value
    b = offset.value
    w = phase.value
    k = freq.value
    # 生成新的数据
    x = np.linspace(0, 4*np.pi, N)
    y = a*np.sin(k*x + w) + b
    source.data = dict(x=x, y=y)
for w in [offset, amplitude, phase, freq]:
    w.on_change('value', update_data)
# 设置显示方式
inputs = column(text, offset, amplitude, phase, freq)
# 服务器托管,win平台在CMD文件路径下运行:bokeh serve sliders.py
# curdoc().add_root(row(inputs, plot, width=800))
# curdoc().title = "Sliders"
# 为便于在notebook展示,将Bokeh数据文档采用如下转换
def fc_doc(doc):
    doc.add_root(row(inputs, plot, width=800))
    doc.title = "Sliders"
show(fc_doc) # 万法皆对象

未经允许不得转载!Bokeh-Web交互

update

纸上得来终觉浅, 绝知此事须躬行。