0

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 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. p is local to the function_to_call() function so should i return p in this function and use it in curdoc().add_root(column(dropdown,p))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.