|
| 1 | +import copy |
| 2 | +from types import NoneType |
| 3 | + |
1 | 4 | import altair as alt |
| 5 | +import pandas as pd |
2 | 6 |
|
3 | | -from chartlets import Component, Input, Output |
| 7 | +from chartlets import Component, Input, Output, State |
4 | 8 | from chartlets.components import Plot, Box, Select |
5 | 9 | from chartlets.demo.contribs import Panel |
6 | 10 | from chartlets.demo.context import Context |
@@ -79,15 +83,45 @@ def make_figure(ctx: Context, selected_dataset: int = 0) -> alt.Chart: |
79 | 83 | .properties(width=290, height=300, title="Vega charts") |
80 | 84 | .add_params(corner_var, click_param) |
81 | 85 | ) |
82 | | - |
83 | 86 | return chart |
84 | 87 |
|
85 | 88 |
|
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