Islam Fahmy
Islam Fahmy

Reputation: 139

Embed hbar bokeh chart into flask app using function

I'm developing a flask app using bokeh and pandas and I want to convert the below hbar script into a function so I can use it in similar data frames,

this is my code

Top_five_all_types_bar_source = ColumnDataSource(Top_five_all_types)
Top_five_all_types_path = Top_five_all_types['con_path'].tolist()
Top_five_all_types_count = Top_five_all_types['Sub_Child_Incident_id']

f_Top_five_all_types= figure(
    y_range=Top_five_all_types_path,
    plot_width =1000,
    plot_height = 300,
    x_axis_label = 'Top Five',


)

f_Top_five_all_types.hbar(
    y='con_path',
    right='Sub_Child_Incident_id',
    left=0,
    height = 0.4,
    source= Top_five_all_types_bar_source
)

hover = HoverTool()
hover.tooltips = """
    <div>Path: @con_path</div>
    <div>Count: @Sub_Child_Incident_id</div>
    <div>Weight: @weight</div>
"""
f_Top_five_all_types.add_tools(hover)

Top_five_all_types_hbar_js, Top_five_all_types_hbar_div = components(f_Top_five_all_types)

I tried this function but it gives me an error Top_five_all_types_hbar_js is not defined

def HBarChart (source,con_path_col,srs_col,weight, labels, script, div):

    top_five_source = ColumnDataSource(source)
    top_five_path_list = source[con_path_col].tolist()
    top_five_count = source[srs_col]

    f = figure(
    y_range=top_five_path_list,
    plot_width =1000,
    plot_height = 300,
    x_axis_label = labels,
    )

    f.hbar(
    y=con_path_col,
    right=srs_col,
    left=0,
    height = 0.4,
    source= top_five_source
    )

    hover = HoverTool()
    hover.tooltips = """
    <div>Path: @con_path_col</div>
    <div>Count: @srs_col</div>
    <div>Weight: @weight</div>
    """
    f.add_tools(hover)

    script, div = components(f)

    return script, div


Top_five_all_types_hbar = HBarChart (
    Top_five_all_types,
    'con_path',
    'Sub_Child_Incident_id',
    'weight',
    'Top Five',
    Top_five_all_types_hbar_js,
    Top_five_all_types_hbar_div
    )

The result should be like the below image Hbar Image

Upvotes: 0

Views: 57

Answers (1)

Eugene Pakhomov
Eugene Pakhomov

Reputation: 10697

The function that you have come up with accepts script and div and never uses them. Instead, it creates and returns them. Try changing the signature to

def HBarChart (source,con_path_col,srs_col,weight, labels):
    ...

And the usage to

Top_five_all_types_hbar_js, Top_five_all_types_hbar_div = HBarChart (
    Top_five_all_types,
    'con_path',
    'Sub_Child_Incident_id',
    'weight',
    'Top Five'
    )

Upvotes: 1

Related Questions