首页 > 解决方案 > Python 。CustomJS 不起作用 js_on_change ,散景滑块

问题描述

有代码必须在地图上显示一些数据,比如说一些数字(年份),问题是 CustomJs 甚至没有调用,滑块上的数据不起作用

def json_data(selectedYear):
   yr = selectedYear
   df_yr = df[df['year'] == yr]
   merged = gdf.merge(df_yr, left_on='country_code', right_on='code', how='left')
   merged.fillna('0', inplace=True)
   merged_json = json.loads(merged.to_json())
   json_data = json.dumps(merged_json)
   return json_data

geosource = GeoJSONDataSource(geojson=json_data(61))

palette = brewer['YlGnBu'][8]

palette = palette[::-1]

color_mapper = LinearColorMapper(palette=palette, low=0, high=40, nan_color='#d9d9d9')

tick_labels = {'0': '0%', '5': '5%', '10': '10%', '15': '15%', '20': '20%', '25': '25%','30': '30%', '35': '35%','40': '>40%'}

hover = HoverTool(tooltips=[('Country/region', '@country'), ('% obesity', '@per_cent_obesity')])

color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8, width=500, height=20,
                 border_line_color=None, location=(0, 0), orientation='horizontal',
                 major_label_overrides=tick_labels)
p = figure(title='Share of adults who are obese, 2016', plot_height=600, plot_width=950,     toolbar_location=None,
       tools=[hover])
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None

p.patches('xs', 'ys', source=geosource, fill_color={'field': 'per_cent_obesity', 'transform': color_mapper},
      line_color='black', line_width=0.25, fill_alpha=1)

p.add_layout(color_bar, 'below')

slider = Slider(title='Year', start=-21, end=61, step=1, value=61)


updatee = CustomJS(args=dict(slider=slider,source=geosource), code="""  
const yr = slider.value;
const new_data = json_data(yr);
const geosource.geojson = new_data;
const p.title.text = 'Share of adults who are obese, %d' % yr;
geosource.change.emit();
""")

但如果我使用而不是更新这个方法:

def update_plot(attr, old, new):
    yr = slider.value
    new_data = json_data(yr)
    geosource.geojson = new_data
    p.title.text = 'Share of adults who are obese, %d' % yr

滑块值正在更改,但数据没有

slider.js_on_change('value', updatee)
layout = column(p, Column(slider))
curdoc().add_root(layout)

output_file("output_file_text.html") 
show(layout)

标签: pythonbokehjs

解决方案


推荐阅读