Python,Bokeh:如何在流图中为线字形分配额外的y轴?

时间:2017-03-15 15:58:14

标签: python streaming bokeh

我的问题可以简化为两行和两个y轴的流图。每条线都分配给不同的y轴。使用Select Widget我想选择分配给主/辅轴的行。

此功能实际上在以下代码中有效。但是,轴分配仅在绘图更新其数据时更改。我希望在更改选择小部件时进行轴分配。

我尝试了几个'更新'功能,但它们都不起作用。我假设'stream'函数更新了轴赋值。如何更改选择小部件?

# Import libraries
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, Range1d, LinearAxis
from bokeh.models.widgets import Button, Select
from bokeh.layouts import layout
from bokeh.plotting import figure
from random import randrange


# Create figure
f=figure()

# Create ColumnDataSource
source_01 = ColumnDataSource(dict(x=[],y=[]))
source_02 = ColumnDataSource(dict(x=[],y=[]))

# Create extra axis
extra_axis = f.extra_y_ranges = {"y2Range": Range1d(start=-10, end=10)}
f.add_layout(LinearAxis(y_range_name='y2Range'), 'left')

# Create Line
line_01 = f.line(x='x',y='y', color='blue', source=source_01, y_range_name='default')
line_02 = f.line(x='x',y='y', color='red' , source=source_02, y_range_name='y2Range')

# Update data
def update_all():
    new_data_01=dict(x=[randrange(1,10)],y=[randrange(1,10)])
    new_data_02=dict(x=[randrange(1,100)],y=[randrange(1,100)])
    source_01.stream(new_data_01,rollover=15)
    source_02.stream(new_data_02,rollover=15)

# Update axis function
def update_axis():
    f.extra_y_ranges['y2Range'].start = -20 #new secondary axis min
    f.extra_y_ranges['y2Range'].end = 80 #new secondary axis max
    f.y_range.start = 0 
    f.y_range.end   = 50

# Select Axis
def update_select_axis(attr, old, new):    
    if select.value == "Red":
        line_01.y_range_name = 'y2Range'
        line_02.y_range_name = 'default'
        line_01.update()
        line_02.update()
        f.update()
        f.y_range.update()
        f.extra_y_ranges.update()
        print('Primary axis: Red, Secondary Axis: BLue')
    elif select.value == "Blue":
        line_01.y_range_name = 'default'
        line_02.y_range_name = 'y2Range'
        line_01.update()
        line_02.update()
        f.update()
        f.y_range.update()
        f.extra_y_ranges.update()
        print('Primary axis: Blue, Secondary Axis: Red')

# Create Select
select = Select(title="Primary Y Axis:", value="Blue", options=["Red", "Blue"])

# Create Button
button = Button(label='Set Axes')

# Update axis range on click
button.on_click(update_axis)
select.on_change("value", update_select_axis)

# Add elements to curdoc 
lay_out=layout([[f, button, select]])
curdoc().add_root(lay_out)
curdoc().add_periodic_callback(update_all,5000)

0 个答案:

没有答案