为什么我的bokeh服务器应用程序不会更新该图

问题描述 投票:0回答:1

这是我的数据:https://drive.google.com/drive/folders/1CabmdDQucaKW2XhBxQlXVNOSiNRtkMm-?usp=sharing我想使用选择来选择要显示的股票;和滑块选择我要显示的年份范围;和复选框组选择要与之比较的索引。问题是当我调整滑块时,图形会更新,但是当我使用选择和复选框组时,图形将不会更新,是什么原因?

from bokeh.io import curdoc
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Slider, TextInput , Select , Div, CheckboxGroup
from bokeh.plotting import figure
import pandas as pd
import numpy as np

price=pd.read_excel('price.xlsx',index_col=0)
# input control

stock = Select(title='Stock',value='AAPL',options=[x for x in list(price.columns) if x not in ['S&P','DOW']])
yr_1 = Slider(title='Start year',value=2015,start=2000,end=2020,step=1)
yr_2 = Slider(title='End year',value=2020,start=2000,end=2020,step=1)
index = CheckboxGroup(labels=['S&P','DOW'],active=[0,1])

def get_data():
    compare_index = [index.labels[i] for i in index.active]
    stocks = stock.value
    start_year = str(yr_1.value)
    end_year = str(yr_2.value)

    select_list = []
    select_list.append(stocks)
    select_list.extend(compare_index)
    selected = price[select_list]
    selected = selected [start_year:end_year]
    for col in selected.columns:
        selected[col]=selected[col]/selected[col].dropna()[0]

    return ColumnDataSource(selected)

def make_plot(source):
    fig=figure(plot_height=600, plot_width=700, title="",sizing_mode="scale_both", x_axis_type="datetime")
    data_columns = list(source.data.keys())
    for data in data_columns[1:]:
        fig.line(x=data_columns[0],y=data,source=source,line_width=3, line_alpha=0.6, legend_label=data)
    return fig

def update(attrname, old, new):
    new_source = get_data()

    source.data.clear()
    source.data.update(new_source.data)


#get the initial value and plot
source = get_data()
plot = make_plot(source)

#control_update

stock.on_change('value', update)
yr_1.on_change('value', update)
yr_2.on_change('value', update)
index.on_change('active', update)


# Set up layouts and add to document
inputs = column(stock, yr_1, yr_2, index)

curdoc().add_root(row(inputs, plot, width=800))
curdoc().title = "Stocks"
python bokeh
1个回答
0
投票

您正在为新数据创建一个新的ColumnDataSource。那不是一个好方法。而是创建一次,然后根据需要分配其data

在您的情况下,我会这样:

  1. 如上所述仅创建一次ColumnDataSource
  2. 不要在CDS上使用.update,只需重新分配.data
  3. 手动创建图例
  4. 对于容易受到选择更改影响的那一行,请选择一个静态的x字段,并在所有地方使用它,代替
  5. 更改第一个图例项目的标签时,将选择的值更改为x字段,而不是它具有正确的名称
© www.soinside.com 2019 - 2024. All rights reserved.