未使用下拉菜单选择更新散景图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了未使用下拉菜单选择更新散景图相关的知识,希望对你有一定的参考价值。
我正在尝试使用Bokeh在各个城市创建一个阳光(日光)小时的互动情节。我使用Bokeh画廊示例“天气”作为指导,因为这是我第一次尝试使用Bokeh。该图表有效,但从下拉菜单中选择新城市时不会更新。将非常感谢帮助识别我的错误。我为这个简单的插图创建了一些示例数据点;实际代码将读取hdf文件。
码:
import pandas as pd
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, DataRange1d, Select
from bokeh.plotting import figure, show
from bokeh.palettes import inferno
variables = ['sunlight_hours']#, 'Sunrise', 'Sunset']
def get_dataset(src, name, plottype):
df = pd.DataFrame()
df['date'] = pd.to_datetime(t)
df['sun'] = src[name]
return ColumnDataSource(data=df)
def make_plot(source, title, city):
plot = figure(x_axis_type="datetime", plot_width=800, tools="", toolbar_location=None)
plot.title.text = title
plot.line(pd.to_datetime(t),sunlight[city]
,line_width=2,line_color=clrs[1],legend=city)
# fixed attributes
plot.xaxis.axis_label = None
plot.yaxis.axis_label = "Sunlight [hours]"
plot.axis.axis_label_text_font_style = "bold"
#plot.x_range = DataRange1d(range_padding=0.0)
plot.grid.grid_line_alpha = 0.3
return plot
def update_plot(attrname, old, new):
new_city = city_select.value
plot.title.text = "Sunlight data for " + new_city
src_update = get_dataset(sunlight, new_city, plottype_select.value)
source.data.update(src_update.data)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
i_city = 'Toronto'
plottype = 'sunlight_hours'
# make example data
yr = 2018
sites = pd.Series(['Resolute','Edmonton','Toronto'])
provs = pd.Series(['Nunavut','Alberta','Ontario'])
sunlight = pd.DataFrame()
sunlight['Toronto'] = pd.Series( [10,11,12,13,12,11,10] )
sunlight['Edmonton'] = pd.Series( [6,8,12,14,11,7,5] )
sunlight['Resolute'] = pd.Series( [4,6,10,16,11,5,2] )
t = pd.date_range('1-1-' + str(yr),periods=7,freq='m')
N = len(sites)
clrs = inferno(N)
cities = {}
for i in range(0,N):
cities.update({sites[i]: {'city': sites[i], 'province':
provs[i],'sun_hrs':sunlight[sites[i]],}})
city_select = Select(value=i_city, title='City', options=sorted(cities.keys()))
plottype_select = Select(value=plottype, title='Plot type', options=['Sunlight']) #, 'Sunrise', 'Sunset'])
source = get_dataset(sunlight, cities[i_city]['city'], plottype)
plot = make_plot(source, "Sunlight data for ",i_city)# + cities[city]['city'])
city_select.on_change('value', update_plot)
plottype_select.on_change('value', update_plot)
controls = column(city_select, plottype_select)
curdoc().add_root(row(plot, controls))
curdoc().title = "Sunlight"
答案
除了绘制线条的方式外,你做的一切都很正确。您直接使用数据而不是ColumnDataSource,因此您正在更新数据源,但没有任何反应,因为渲染器不使用它。
更改
plot.line(pd.to_datetime(t),sunlight[city],line_width=2,line_color=clrs[1],legend=city)
至
plot.line('date','sun',line_width=2,line_color=clrs[1],legend=city,source=source)
传递源名称和字段名称,而不是传递实际数组
以上是关于未使用下拉菜单选择更新散景图的主要内容,如果未能解决你的问题,请参考以下文章