Pie chart - selected parameter - On click on pie chart slice, data on below bar chart are changing but I am able to see same function is called multiple times #2485
-
On click of pie chart, clicked slice its getting pulled and two bar chart below it got changed accordingly as expected. But we are able to see slowness in that and when i checked, it looks like same function is called multiple times. can you please help on this? Attached the code and csv file used for reference. from datetime import datetime
import numpy as np
import pandas as pd
import plotly.express as px
import taipy.gui.builder as tgb
from taipy import Gui
from taipy.gui import Gui, State
def pie_charts(dates):
cnv_start_date = dates[0].strftime("%Y-%m-%d")
cnv_end_date = dates[1].strftime("%Y-%m-%d")
intial_flter_bkgs = df_total_bkgs.query(
"booked_date >= @cnv_start_date and booked_date <= @cnv_end_date"
)
bkgs_ct = (
intial_flter_bkgs.groupby(["Booking_type"]).size().reset_index(name="count")
)
total_bkgs = bkgs_ct["count"].sum()
return bkgs_ct
def base_online_bkgs(dates):
cnv_start_date = dates[0].strftime("%Y-%m-%d")
cnv_end_date = dates[1].strftime("%Y-%m-%d")
df_summary_2 = df_total_bkgs.query(
"booked_date >= @cnv_start_date and booked_date <= @cnv_end_date"
)
fltr_base_bkgs = df_summary_2.groupby(["customer_code"]).size()
top_ten_customers = (
fltr_base_bkgs.reset_index(name="Bookings_Count")
.sort_values("Bookings_Count", ascending=False)
.head(10)
)
customer = px.bar(
top_ten_customers,
x="Bookings_Count",
y="customer_code",
orientation="h",
color="customer_code",
text="Bookings_Count",
)
customer.update_traces(
width=0.8,
textposition="inside",
)
customer.update_layout(bargap=0.6)
return customer
def base_online_teu(dates):
cnv_start_date = dates[0].strftime("%Y-%m-%d")
cnv_end_date = dates[1].strftime("%Y-%m-%d")
intial_base_bkgs = df_total_bkgs.query(
"booked_date >= @cnv_start_date and booked_date <= @cnv_end_date"
)
fltr_base_bkgs = intial_base_bkgs.groupby(["customer_code"]).sum().reset_index()
fltr_base_teu = fltr_base_bkgs[["customer_code", "booked_teu"]]
top_ten_customers = fltr_base_teu.sort_values("booked_teu", ascending=False).head(
10
)
customer_teu = px.bar(
top_ten_customers,
x="booked_teu",
y="customer_code",
orientation="h",
color="customer_code",
text="booked_teu",
)
customer_teu.update_traces(
width=0.8,
textposition="inside",
)
customer_teu.update_layout(bargap=0.6)
return customer_teu
def button_click(state):
state = state
state.pie_data = pie_charts(state.dates)
state.convert_start = str(state.dates[0].strftime("%b %d %Y"))
state.convert_end = str(state.dates[1].strftime("%b %d %Y"))
state.base_bkg_fig = base_online_bkgs(state.dates)
def on_change(state: State, var_name: str, var_value):
print(datetime.now(), "Start of the clicked activity")
# print("Pie chart click activity function is activated....", datetime.now())
if not state.selected:
return # Exit if no selection is made
selected_index = state.selected[0] # Get the clicked index
# print("Selected index:", selected_index)
# Get current pull values
pull_values = state.intial_options["pull"]
# print("Current pull values:", pull_values)
# Toggle logic: If already pulled, reset to [0, 0, 0], else pull the selected slice
if pull_values[selected_index] == 0.2:
new_pull_values = [0] * len(pull_values) # Reset all
state.base_bkg_fig = base_online_bkgs(state.dates)
state.base_teu_fig = base_online_teu(state.dates)
else:
new_pull_values = [
0.2 if i == selected_index else 0 for i in range(len(pull_values))
]
# print("dates", state.dates)
# print("booking_type", state.pie_data["booking_type"][selected_index])
state.base_bkg_fig = base_online_bkgs_booking_type(
state.dates, state.pie_data["Booking_type"][selected_index]
)
state.base_teu_fig = base_online_teu_booking_type(
state.dates, state.pie_data["Booking_type"][selected_index]
)
# print("Updated pull values:", new_pull_values)
# Assign updated pull values
state.intial_options["pull"] = new_pull_values
# Force re-render by reassigning the dictionary reference
state.intial_options = dict(state.intial_options)
print(datetime.now(), "End of the clicked activity")
def base_online_bkgs_booking_type(dates, Booking_type):
cnv_start_date = dates[0].strftime("%Y-%m-%d")
cnv_end_date = dates[1].strftime("%Y-%m-%d")
bk_type = Booking_type
intial_base_bkgs = df_total_bkgs.query(
"booked_date >= @cnv_start_date and booked_date <= @cnv_end_date and Booking_type ==@bk_type"
)
fltr_base_bkgs = intial_base_bkgs.groupby(["customer_code"]).size()
top_ten_customers = (
fltr_base_bkgs.reset_index(name="Bookings_Count")
.sort_values("Bookings_Count", ascending=False)
.head(10)
)
customer = px.bar(
top_ten_customers,
x="Bookings_Count",
y="customer_code",
orientation="h",
color="customer_code",
text="Bookings_Count",
# hover_data=["Customer_Code", "Bookings_Count"],
# height=400,
# title="Restaurant bills",
)
customer.update_traces(
width=0.8,
textposition="inside",
# text=[35, 32, 23, 19, 16, 15, 13, 13, 12],
)
customer.update_layout(bargap=0.6)
return customer
def base_online_teu_booking_type(dates, Booking_type):
cnv_start_date = dates[0].strftime("%Y-%m-%d")
cnv_end_date = dates[1].strftime("%Y-%m-%d")
bk_type = Booking_type
intial_base_bkgs = df_total_bkgs.query(
"booked_date >= @cnv_start_date and booked_date <= @cnv_end_date and Booking_type ==@bk_type"
)
fltr_base_bkgs = intial_base_bkgs.groupby(["customer_code"]).sum().reset_index()
# fltr_base_bkgs.to_csv("check_teu1.csv")
fltr_base_teu = fltr_base_bkgs[["customer_code", "booked_teu"]]
# fltr_base_teu.to_csv("check_teu2.csv")
top_ten_customers = fltr_base_teu.sort_values("booked_teu", ascending=False).head(
10
)
customer_teu = px.bar(
top_ten_customers,
x="booked_teu",
y="customer_code",
orientation="h",
color="customer_code",
text="booked_teu",
# hover_data=["Customer_Code", "Bookings_Count"],
# height=400,
# title="Restaurant bills",
)
customer_teu.update_traces(
width=0.8,
textposition="inside",
# text=[35, 32, 23, 19, 16, 15, 13, 13, 12],
)
customer_teu.update_layout(bargap=0.6)
return customer_teu
end_date = datetime.today().date()
start_date = end_date.replace(day=1)
dates = [start_date, end_date]
selected = []
df_total_bkgs = pd.read_csv(r"shipping_bookings.csv")
# df_summary = pd.read_csv(r"summary_1.csv")
convert_start = str(start_date.strftime("%b %d %Y"))
convert_end = str(end_date.strftime("%b %d %Y"))
cnv_start_date = start_date.strftime("%Y-%m-%d")
cnv_end_date = end_date.strftime("%Y-%m-%d")
base_bkg_fig = base_online_bkgs(dates)
base_teu_fig = base_online_teu(dates)
pie_data = pie_charts(dates)
total_bkg = pie_data["count"].sum()
intial_options = {
"hole": 0.6,
"pull": [0, 0, 0],
"textfont": {"size": 18},
"hoverlabel": {
"font": {"size": 12, "color": "white"}, # Hover text color
"bgcolor": "black", # Hover background color
},
"hovertemplate": "<b>%{label}</b><br>Bookings: %{value}<br>Percentage: %{percent}", # Custom hover text,
"insidetextorientation": "horizontal",
}
marker = {"colors": ("rgb(255,250,220)", "rgb(230,200,0)", "rgb(160,90,0)")}
layout = {
"height": 575,
"annotations": [
{
"text": "Total Bookings<br>" + str(total_bkg),
"showarrow": False,
"font": {"size": 25},
}
],
"showlegend": True,
}
with tgb.Page() as page:
with tgb.part(class_name="container"):
tgb.text(
value="# Booking Dashboard",
mode="md",
class_name="text-center text-color",
)
with tgb.layout(columns="0.8 1", class_name="card"): # custom-bkg
with tgb.part():
tgb.date_range(
"{dates}", label_start="Start-date", label_end="End-date"
)
with tgb.part():
tgb.button(
"Apply",
class_name="plain",
on_action=button_click,
)
tgb.html("br")
with tgb.layout(columns="1"):
with tgb.part(class_name="card text-center"):
tgb.text(
"Bookings from {convert_start} - {convert_end}",
class_name="text-chnges",
)
tgb.chart(
"{pie_data}",
type="pie",
values="count",
labels="Booking_type",
marker="{marker}",
options="{intial_options}",
layout="{layout}",
# on_click=pie_click,
selected="{selected}",
rebuild=True,
)
tgb.html("br")
with tgb.layout(columns="1 1"):
with tgb.part(class_name="card "):
tgb.text(
"Top 10 Customers by Booking",
class_name="text-chnges",
)
tgb.chart(figure="{base_bkg_fig}")
with tgb.part(class_name="card "):
tgb.text(
"Top 10 Customers by TEU",
class_name="text-chnges",
)
tgb.chart(figure="{base_teu_fig}")
Gui(page=page).run(debug=True, port=5005, use_reloader=True, dark_mode=True) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Your on_change is called whenever a variable is being changed through the User Interface or when you do: You must add an if statement to this callback in order to do the function only when you need it: def on_change(state: State, var_name: str, var_value):
if var_name == "selected": # or var_name in ["selected", ...] depending on what the logic of your app is
... |
Beta Was this translation helpful? Give feedback.
Your on_change is called whenever a variable is being changed through the User Interface or when you do:
state.xxx =
.You must add an if statement to this callback in order to do the function only when you need it: