Skip to content

Commit efdc7d3

Browse files
committed
Access the click event in the callback function
1 parent 192783e commit efdc7d3

File tree

1 file changed

+44
-10
lines changed

1 file changed

+44
-10
lines changed

chartlets.py/my_extension/my_panel_1.py

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
import copy
2+
from types import NoneType
3+
14
import altair as alt
5+
import pandas as pd
26

3-
from chartlets import Component, Input, Output
7+
from chartlets import Component, Input, Output, State
48
from chartlets.components import Plot, Box, Select
59
from chartlets.demo.contribs import Panel
610
from chartlets.demo.context import Context
@@ -79,15 +83,45 @@ def make_figure(ctx: Context, selected_dataset: int = 0) -> alt.Chart:
7983
.properties(width=290, height=300, title="Vega charts")
8084
.add_params(corner_var, click_param)
8185
)
82-
8386
return chart
8487

8588

86-
# # TODO: see if we can get the value of the clicked points from the click params above
87-
# @panel.callback(
88-
# Input("selected_dataset"),
89-
# Output("plot", "chart"),
90-
# )
91-
# def test_callback(
92-
# self,
93-
# ): ...
89+
@panel.callback(
90+
Input("plot", property="points"), State("plot", "chart"), Output("plot", "chart")
91+
)
92+
def get_click_event_points(ctx: Context, points, plot) -> alt.Chart:
93+
"""
94+
This callback function shows how we can use the event handlers output
95+
(property="points") which was defined in the `make_figure` callback
96+
function as a `on='click'` handler. Here, we access the variables as
97+
defined in the `fields` argument when creating the `click_param` parameter.
98+
99+
Based on the click event, the user can access the point that was clicked.
100+
The function below extracts the points and changes the color of the bar
101+
that was clicked.
102+
103+
"""
104+
if points:
105+
conditions = []
106+
for field, values in points.items():
107+
if field != "vlPoint":
108+
for value in values:
109+
field_type = plot["encoding"].get(field, {}).get("type", "")
110+
if field_type == "nominal":
111+
conditions.append(f"datum.{field} === '{value}'")
112+
else:
113+
conditions.append(f"datum.{field} === {value}")
114+
conditions.append(f"datum.{field} === {repr(value)}")
115+
116+
condition_expr = " && ".join(conditions)
117+
118+
plot["encoding"]["color"] = {
119+
"condition": {
120+
"test": condition_expr,
121+
# Highlight color when the condition is true
122+
"value": "orange",
123+
},
124+
"value": "steelblue", # Default color
125+
}
126+
127+
return alt.Chart.from_dict(plot)

0 commit comments

Comments
 (0)