我知道为什么我的 y_range 没有更新。如果我独立设置 y_range.max ,那么以后我不能在 update() 函数中“重新设置”它。但是,如果我在声明图形时进行设置,那么我可以更新我的 update() 函数中的值。这是 Bokeh 的预期行为吗?
import pandas as pd
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Button
def populate_table_source(df):
ds = {}
for col in list(df):
ds[col] = df[col]
return ds
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
years = ['2015', '2016', '2017']
data = {'fruits': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 4, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]}
df_chart = pd.DataFrame(data)
df_chart['total'] = df_chart[years].sum(axis=1)
print(df_chart)
chart_data_source = ColumnDataSource(data={})
chart_data_source.data = populate_table_source(df_chart)
years = ['2015', '2016', '2017']
# set up widgets
button = Button(label="Update", button_type="success")
p = figure(x_range=chart_data_source.data['fruits'],
plot_height=250,
plot_width=1000,
title="Fruit Counts by Year",
tools="hover,save",
tooltips="$name: @$name",
y_range=(0, 10) # can be updated if you assign it here
)
p.vbar_stack(years,
x='fruits',
width=0.9,
color=colors,
source=chart_data_source,
)
# p.y_range.start = 0
# p.y_range.end = 10 # can't be udpated if you assign it here
def update_data():
data = {'fruits': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
'2015': [np.random.randint(5), np.random.randint(5), np.random.randint(5), np.random.randint(5),
np.random.randint(5), np.random.randint(5)],
'2016': [np.random.randint(5), np.random.randint(5), np.random.randint(5), np.random.randint(5),
np.random.randint(5), np.random.randint(5)],
'2017': [np.random.randint(5), np.random.randint(5), np.random.randint(5), np.random.randint(5),
np.random.randint(5), np.random.randint(5)],
}
df_chart = pd.DataFrame(data)
df_chart['total'] = df_chart[years].sum(axis=1)
chart_data_source.data = populate_table_source(df_chart)
old_y_range = p.y_range.end
p.y_range.end = old_y_range + 2
# Set up layout
button.on_click(update_data)
lo = layout(button, p)
curdoc().add_root(lo)
curdoc().title = "MVE"