I have a dataframe including an independent variable (country), and I am going to have an interactive panel to be able to select in the bar charts, according to the country. The bar charts is going to present count of each industry in the selected country. However my code shows the selection panel, it just shows an empty plot!!! and changing the selection does not make any difference.
You can find the code here:
import pandas as pd
from bokeh.plotting import figure
from bokeh.layouts import layout, widgetbox
from bokeh.models import ColumnDataSource, HoverTool, BoxZoomTool, ResetTool, PanTool
from bokeh.models.widgets import Select
from bokeh.models import WheelZoomTool, SaveTool, LassoSelectTool
from bokeh.io import show, output_notebook
output_notebook()
data = pd.DataFrame({'id':['001', '002', '003', '004','005', '006', '007', '008','009', '010', '011', '012','013', '014', '015', '016'],
'country_code':['A', 'A', 'B', 'B','C', 'A', 'C', 'B','A', 'C', 'C', 'A','A', 'A', 'C', 'B'],
'Industry':['M1', 'M2', 'M1', 'M3','M2', 'M3', 'M3', 'M3','M1', 'M2', 'M1', 'M1','M2', 'M1', 'M1', 'M3'],
'Zone':['x', 'x', 'x', 't','y', 'z', 'z', 'z','t', 't', 'y', 'y','z', 't', 'z', 'x'],
'count':[100,200,150,120,200,200,180,100,100,200,150,120,200,200,180,100]})
#Creating the list of country codes
Options = ["All"] + list(data['country_code'].unique())
Countries = Select(title = " Country Code", options = Options, value = "All")
TOOLS = [BoxZoomTool(), LassoSelectTool(), WheelZoomTool(), PanTool(), ResetTool(), SaveTool()]
def select():
""" Use the current selections to determine which filters to apply to the
data. Return a dataframe of the selected data
"""
df = data
# Determine which country has been selected
country_val = Countries.value
if country_val == "All":
selected = pd.DataFrame(df.groupby(['Industry']).size().reset_index())
selected.columns = ['Industry','count']
else:
selected = df[df['country_code'] == country_val]
return selected
def update():
"Get the selected data and update the data in the source"
df_active = select()
source = ColumnDataSource(df_active)
return source
p = figure( plot_height = 300, title = "Inustry_code", tools = TOOLS)
p.vbar(x = 'Industry', top = 'count', width = .9, fill_alpha = .5, fill_color = 'red', line_alpha = .5, source = update())
show(Countries)
show(p)
You need to specify the x_range
like this: x_range = source.data['Industry']
. So your code could be:
source = update()
p = figure( plot_height = 300, title = "Inustry_code", tools = TOOLS, x_range = source.data['Industry'])
p.vbar(x = 'Industry', top = 'count', width = .9, fill_alpha = .5, fill_color = 'red', line_alpha = .5, source = source)
show(Countries)
show(p)