未使用下拉菜单选择更新散景图

时间:2018-02-27 20:03:34

标签: python plot bokeh

我正在尝试使用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"

1 个答案:

答案 0 :(得分:0)

除了绘制线条的方式外,你做的一切都很正确。您直接使用数据而不是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)

不是传递实际数组,而是传递源名称和字段名称