bokeh_app.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from bokeh.io import output_notebook
  2. from bokeh.io import show
  3. from bokeh.layouts import column
  4. from bokeh.models import ColumnDataSource, Slider
  5. from bokeh.plotting import figure
  6. from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
  7. from pywebio import start_server
  8. from pywebio.output import *
  9. from pywebio.session import info as session_info
  10. def bkapp(doc):
  11. df = sea_surface_temperature.copy()
  12. source = ColumnDataSource(data=df)
  13. plot = figure(x_axis_type='datetime', y_range=(0, 25),
  14. y_axis_label='Temperature (Celsius)',
  15. title="Sea Surface Temperature at 43.18, -70.43")
  16. plot.line('time', 'temperature', source=source)
  17. def callback(attr, old, new):
  18. if new == 0:
  19. data = df
  20. else:
  21. data = df.rolling('{0}D'.format(new)).mean()
  22. source.data = ColumnDataSource.from_df(data)
  23. slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
  24. slider.on_change('value', callback)
  25. doc.add_root(column([slider, plot], sizing_mode='stretch_width'))
  26. def main():
  27. output_notebook(verbose=False, notebook_type='pywebio')
  28. if 'zh' in session_info.user_language:
  29. put_markdown("""# Bokeh Applications in PyWebIO
  30. [Bokeh Applications](https://docs.bokeh.org/en/latest/docs/user_guide/server.html) 支持向图表的添加按钮、输入框等交互组件,并向组件添加Python回调,从而创建可以与Python代码交互的可视化图表。
  31. 在PyWebIO中,你也可以使用 `bokeh.io.show()` 来显示一个Bokeh App,和输出普通图表一样,只需要在会话开始时调用 `bokeh.io.output_notebook(notebook_type='pywebio')` 来设置PyWebIO输出环境。
  32. 以下为一个 Bokeh App demo:
  33. """)
  34. else:
  35. put_markdown("""# Bokeh Applications in PyWebIO
  36. [Bokeh Applications](https://docs.bokeh.org/en/latest/docs/user_guide/server.html) can be built by starting the Bokeh server. The purpose of the Bokeh server is to make it easy for Python users to create interactive web applications that can connect front-end UI events to real, running Python code.
  37. In PyWebIO, you can also use bokeh.io.show() to display a Bokeh App.
  38. You can use `bokeh.io.output_notebook(notebook_type='pywebio')` in the PyWebIO session to setup Bokeh environment. Then you can use `bokeh.io.show()` to output a boken application.
  39. This is a demo of Bokeh App:
  40. """)
  41. show(bkapp)
  42. if __name__ == '__main__':
  43. start_server(main, port=8080, debug=True)