How to plot bar graph interactively based on value of dropdown widget in bokeh python?

↘锁芯ラ 提交于 2020-01-25 12:48:09

问题


I want to plot the bar graph based value of dropdown widget.

Code

import pandas as pd
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc
from bokeh.charts import Bar, output_file,output_server, show #use output_notebook to visualize it in notebook


df=pd.DataFrame({'item':["item1","item2","item2","item1","item1","item2"],'value':[4,8,3,5,7,2]})

menu = [("item1", "item1"), ("item2", "item2")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)


def function_to_call(attr, old, new):

    df=df[df['item']==dropdown.value]    
    p = Bar(df, title="Bar Chart Example", xlabel='x', ylabel='values', width=400, height=400)
    output_server()    
    show(p)

dropdown.on_change('value', function_to_call)

curdoc().add_root(dropdown)

Questions

  1. I am getting the flowing error "UnboundLocalError: local variable 'df' referenced before assignment" eventhough df is already created.
  2. How to plot the bar graph in the webpage below the dropdown? What is the syntax to display it after issue in 1. is resolved?

回答1:


For 1.) you are referencing it before assigning it. Look at the df['item']==dropdown.value inside the square brackets. That happens first before the assignment. As to why this matters, that's how Python works. All assignments in a function by default create local variables. But before the assignment, only the global value is available. Python is telling you it won't allow mixed global/local usage in a single function. Long story short, rename the df variable inside the function:

subset = df[df['item']==dropdown.value]    
p = Bar(subset, ...) 

For 2.) you need to put things in a layout (e.g. a column). There are lots of example of this in the project docs and in the gallery.



来源:https://stackoverflow.com/questions/39119140/how-to-plot-bar-graph-interactively-based-on-value-of-dropdown-widget-in-bokeh-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!