I’ve a below code in which I show plotly bar chart. Upon click on bar, I want to display which bar user has selected but the code I’ve written is not working. Please help.
import panel as pn
import param
import pandas as pd
import plotly.express as pltex
pn.extension('plotly')
class Example(param.Parameterized):
df = param.DataFrame()
selected_name = param.String(default='')
def bar_click(self, event):
index = event.new['points'][0]['pointIndex']
current_destination_name = self.df.iloc[index]['sr']
self.selected_name = current_destination_name
def show_data():
ex_obj = Example()
data_list = [{'sr': 'A', 'total': 20},
{'sr': 'B', 'total': 50},
{'sr': 'C', 'total': 10},
{'sr': 'D', 'total': 70},
{'sr': 'E', 'total': 90},]
ex_obj.df = pd.DataFrame(data_list)
fig = pltex.bar(ex_obj.df, y='total', x='sr',
title="Bar Chart")
fig.update_traces(textfont_size=12, textangle=0, textposition="outside", cliponaxis=False)
fig.layout.autosize = True
the_plotly_pane = pn.pane.Plotly(fig, config={'responsive': True})
the_plotly_pane.param.watch(bar_click, 'click_data', onlychanged=False)
gspec = pn.GridSpec()
gspec[0:2, :3] = the_plotly_pane
gspec[2,0] = pn.Column(pn.pane.Markdown(f"## Selected Sr : {ex_obj.selected_name}"), sizing_mode='stretch_width')
tabs = pn.Tabs(('Analytics', gspec))
return tabs
def show(page):
tabs = show_data()
return tabs
page = pn.widgets.RadioButtonGroup(
value='First Page',
options=['First Page', 'Second Page'],
name="Page",
button_type="success",
orientation="vertical")
ishow = pn.bind(show, page=page)
pn.template.FastListTemplate(
title="Data Analytics",
sidebar=[page],
main=[ishow]).servable()
It looks like this in browser.
If I click on B bar then it should show Selected Sr : B but it’s not working currently. Nothing happens clicking on bar.