Dash_tooltip 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,267 @@
1
+ import logging
2
+ import re
3
+ from string import Template
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ import plotly.graph_objs as go
7
+ from dash import Input, Output, State, dash
8
+ from dash.exceptions import PreventUpdate
9
+
10
+ from .config import DEFAULT_ANNOTATION_CONFIG, DEFAULT_TEMPLATE
11
+ from .custom_figure import CustomFigure
12
+ from .utils import _display_click_data, _find_all_graph_ids, add_annotation_store
13
+
14
+ # Logger setup
15
+ logger = logging.getLogger("dash_tooltip")
16
+ logger.setLevel(logging.DEBUG)
17
+
18
+ # File handler setup
19
+ file_handler = logging.FileHandler("dash_app.log")
20
+ file_handler.setLevel(logging.DEBUG)
21
+
22
+ # Create a formatter and add it to the handler
23
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
24
+ file_handler.setFormatter(formatter)
25
+
26
+ # Add the handler to the logger
27
+ logger.addHandler(file_handler)
28
+
29
+ # Prevent logs from being propagated to the root logger
30
+ logger.propagate = False
31
+
32
+ # Now, you can log messages
33
+ logger.debug("dash_tooltip log active")
34
+
35
+ registered_callbacks = set()
36
+ ANNOTATION_RELAYOUT_KEY = re.compile(r"annotations\[(\d+)\]\.(.+)")
37
+
38
+
39
+ def _apply_annotation_relayout(
40
+ current_figure: Dict[str, Any], relayout_data: Dict[str, Any]
41
+ ) -> bool:
42
+ """Persist client-side annotation edits back into the server-side figure."""
43
+ if not relayout_data:
44
+ return False
45
+
46
+ annotation_updates: Dict[int, Dict[str, Any]] = {}
47
+ for key, value in relayout_data.items():
48
+ match = ANNOTATION_RELAYOUT_KEY.fullmatch(key)
49
+ if not match:
50
+ continue
51
+
52
+ index = int(match.group(1))
53
+ property_name = match.group(2)
54
+ annotation_updates.setdefault(index, {})[property_name] = value
55
+
56
+ if not annotation_updates:
57
+ return False
58
+
59
+ layout = current_figure.get("layout")
60
+ if not isinstance(layout, dict):
61
+ return False
62
+
63
+ annotations = layout.get("annotations", [])
64
+ if not isinstance(annotations, list) or not annotations:
65
+ return False
66
+
67
+ changed = False
68
+ for index, properties in annotation_updates.items():
69
+ if index >= len(annotations):
70
+ continue
71
+ annotation = annotations[index]
72
+ if not isinstance(annotation, dict):
73
+ annotation = dict(annotation)
74
+ annotation.update(properties)
75
+ annotations[index] = annotation
76
+ changed = True
77
+
78
+ if changed:
79
+ layout["annotations"] = annotations
80
+ return changed
81
+
82
+
83
+ class TooltipManager:
84
+ def __init__(
85
+ self,
86
+ app: dash.Dash,
87
+ style: Dict[Any, Any],
88
+ template: str,
89
+ graph_ids: List[str],
90
+ apply_log_fix: bool,
91
+ debug: bool,
92
+ ):
93
+ self.figures = {graph_id: CustomFigure() for graph_id in graph_ids}
94
+ self.templates = {graph_id: template for graph_id in graph_ids}
95
+ self.style = style
96
+ self.apply_log_fix = apply_log_fix
97
+ self.debug = debug
98
+ self.app = app
99
+ self.graph_ids = graph_ids
100
+ self.tooltip_active = True # Default to active
101
+ self.initialize_callbacks()
102
+
103
+ def update_template(self, graph_id: str, template: str):
104
+ if graph_id in self.figures:
105
+ self.templates[graph_id] = template
106
+ self.figures[graph_id].update_template(template)
107
+
108
+ def initialize_callbacks(self):
109
+ for graph_id in self.graph_ids:
110
+ callback_identifier = (graph_id, "figure")
111
+ if callback_identifier in registered_callbacks:
112
+ # Skip reattaching if already registered
113
+ continue
114
+ registered_callbacks.add(callback_identifier)
115
+
116
+ # Check for valid graph ID and add annotation store
117
+ if graph_id not in self.app.layout:
118
+ raise ValueError(f"Invalid graph ID provided: {graph_id}")
119
+ add_annotation_store(self.app.layout, graph_id)
120
+
121
+ @self.app.callback(
122
+ Output(component_id=graph_id, component_property="figure"),
123
+ Input(component_id=graph_id, component_property="clickData"),
124
+ State(component_id=graph_id, component_property="figure"),
125
+ )
126
+ def display_click_data(
127
+ clickData: Dict[str, Any],
128
+ figure: Union[CustomFigure, Dict[str, Any]],
129
+ ) -> CustomFigure:
130
+ """Display data on click event."""
131
+ if not self.tooltip_active:
132
+ raise PreventUpdate
133
+
134
+ if figure is None:
135
+ figure = CustomFigure()
136
+
137
+ template = self.templates[graph_id]
138
+ if isinstance(figure, CustomFigure):
139
+ return _display_click_data(clickData, figure, template, self.style)
140
+ # Check if figure is a dictionary
141
+ elif isinstance(figure, dict):
142
+ # Extract data and layout from the figure dictionary
143
+ raw_data = figure.get("data", [])
144
+ layout = figure.get("layout", {})
145
+
146
+ # Convert dictionary representations of traces into actual trace objects
147
+ data = []
148
+ for trace in raw_data:
149
+ trace_type = trace.pop("type")
150
+ trace_class = getattr(go, trace_type.capitalize())
151
+ data.append(trace_class(**trace))
152
+
153
+ # Construct the CustomFigure(go.Figure) using data and layout
154
+ custom_figure = CustomFigure(data=data, layout=layout)
155
+ return _display_click_data(
156
+ clickData, custom_figure, template, self.style
157
+ )
158
+ else:
159
+ custom_figure = CustomFigure(figure)
160
+ return _display_click_data(
161
+ clickData, custom_figure, template, self.style
162
+ )
163
+
164
+ @self.app.callback(
165
+ Output(graph_id, "figure", allow_duplicate=True),
166
+ Input(graph_id, "relayoutData"),
167
+ State(graph_id, "figure"),
168
+ prevent_initial_call=True,
169
+ )
170
+ def persist_annotation_relayout(
171
+ relayout_data: Dict[str, Any], current_figure: Dict[str, Any]
172
+ ) -> Union[Dict[str, Any], dash._callback.NoUpdate]:
173
+ """Persist dragged or edited annotation properties."""
174
+ if current_figure and _apply_annotation_relayout(
175
+ current_figure, relayout_data
176
+ ):
177
+ return current_figure
178
+ return dash.no_update
179
+
180
+ @self.app.callback(
181
+ Output(graph_id, "figure", allow_duplicate=True),
182
+ Input(f"tooltip-annotations-to-remove-{graph_id}", "data"),
183
+ State(graph_id, "figure"),
184
+ prevent_initial_call=True,
185
+ )
186
+ def remove_empty_annotations(
187
+ indices_to_remove: List[int], current_figure: Dict[str, Any]
188
+ ) -> Union[Dict[str, Any], dash._callback.NoUpdate]:
189
+ """Remove annotations that have been deleted by the user."""
190
+ if indices_to_remove:
191
+ annotations = current_figure["layout"].get("annotations", [])
192
+ logger.debug(f"Original Annotations: {annotations}")
193
+ updated_annotations = [
194
+ anno
195
+ for idx, anno in enumerate(annotations)
196
+ if idx not in indices_to_remove
197
+ ]
198
+ logger.debug(f"Indices to Remove: {indices_to_remove}")
199
+ logger.debug(f"Updated Annotations: {updated_annotations}")
200
+ current_figure["layout"]["annotations"] = updated_annotations
201
+ return current_figure
202
+ return dash.no_update
203
+
204
+ # Client-side callback to identify annotations to remove
205
+ dbg_str = "console.log(relayoutData);" if self.debug else ""
206
+ self.app.clientside_callback(
207
+ Template(
208
+ """
209
+ function(relayoutData) {
210
+ $dbg_str
211
+ var annotationPattern = /annotations\\[(\\d+)\\].text/;
212
+ var indicesToRemove = [];
213
+ for (var key in relayoutData) {
214
+ var match = key.match(annotationPattern);
215
+ if (match && relayoutData[key] === "") {
216
+ indicesToRemove.push(parseInt(match[1]));
217
+ }
218
+ }
219
+ return indicesToRemove;
220
+ }
221
+ """
222
+ ).substitute(dbg_str=dbg_str),
223
+ Output(f"tooltip-annotations-to-remove-{graph_id}", "data"),
224
+ Input(graph_id, "relayoutData"),
225
+ )
226
+
227
+
228
+ def tooltip(
229
+ app: dash.Dash,
230
+ style: Dict[Any, Any] = DEFAULT_ANNOTATION_CONFIG,
231
+ template: str = DEFAULT_TEMPLATE,
232
+ graph_ids: Optional[List[str]] = None,
233
+ apply_log_fix: bool = True,
234
+ debug: bool = False,
235
+ ) -> TooltipManager:
236
+ """
237
+ Add tooltip functionality to Dash graph components.
238
+
239
+ Args:
240
+ app (dash.Dash): The Dash app instance.
241
+ style (dict): Configuration for the tooltip appearance.
242
+ Users can provide any valid Plotly annotation style options.
243
+ template (str): The default annotation template.
244
+ Default is a basic string template.
245
+ graph_ids (list, optional): List of graph IDs to apply tooltips to.
246
+ If not provided, will try to auto-detect from the layout.
247
+ apply_log_fix (bool): If True, applies a fix for logging issues.
248
+ debug (bool): If True, enables debugging mode.
249
+
250
+ Returns:
251
+ TooltipManager: An instance of TooltipManager class.
252
+ """
253
+ if graph_ids is None:
254
+ graph_ids = _find_all_graph_ids(app.layout)
255
+ if not graph_ids:
256
+ raise ValueError(
257
+ "No graphs found in the app layout. Please provide a graph ID."
258
+ )
259
+ return TooltipManager(app, style, template, graph_ids, apply_log_fix, debug)
260
+
261
+
262
+ __all__ = [
263
+ "tooltip",
264
+ "add_annotation_store",
265
+ "DEFAULT_ANNOTATION_CONFIG",
266
+ "DEFAULT_TEMPLATE",
267
+ ]
@@ -0,0 +1,21 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
5
+
6
+ TYPE_CHECKING = False
7
+ if TYPE_CHECKING:
8
+ from typing import Tuple
9
+ from typing import Union
10
+
11
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
12
+ else:
13
+ VERSION_TUPLE = object
14
+
15
+ version: str
16
+ __version__: str
17
+ __version_tuple__: VERSION_TUPLE
18
+ version_tuple: VERSION_TUPLE
19
+
20
+ __version__ = version = '0.4.3.dev0+gc0d76c5.d20250329'
21
+ __version_tuple__ = version_tuple = (0, 4, 3, 'dev0', 'gc0d76c5.d20250329')
dash_tooltip/config.py ADDED
@@ -0,0 +1,18 @@
1
+ DEFAULT_ANNOTATION_CONFIG = {
2
+ # horizontal alignment of the text (can be 'left', 'center', or 'right')
3
+ "align": "left",
4
+ "arrowcolor": "black", # color of the annotation arrow
5
+ "arrowhead": 3, # type of arrowhead, for Plotly (an integer from 0 to 8)
6
+ "arrowsize": 1.8, # relative size of the arrowhead to the arrow stem, for Plotly
7
+ "arrowwidth": 1, # width of the annotation arrow in pixels, for Plotly
8
+ "font": {
9
+ "color": "black", # color of the annotation text
10
+ "family": "Arial", # font family of the annotation text, for Plotly
11
+ "size": 12, # size of the annotation text in points, for Plotly
12
+ },
13
+ "showarrow": True,
14
+ # horizontal alignment of the text (can be 'left', 'center', or 'right')
15
+ "xanchor": "left",
16
+ }
17
+
18
+ DEFAULT_TEMPLATE = "x: %{x},<br>y: %{y}"
@@ -0,0 +1,12 @@
1
+ import plotly.graph_objs as go
2
+
3
+ from dash_tooltip import DEFAULT_TEMPLATE
4
+
5
+
6
+ class CustomFigure(go.Figure):
7
+ def __init__(self, *args, **kwargs):
8
+ super().__init__(*args, **kwargs)
9
+ self._tooltip_template = DEFAULT_TEMPLATE
10
+
11
+ def update_template(self, template):
12
+ self.layout._tooltip_template = template
dash_tooltip/utils.py ADDED
@@ -0,0 +1,324 @@
1
+ import json
2
+ import logging
3
+ import math
4
+ import re
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ import dash
8
+ import plotly.graph_objs as go
9
+ from dash import dcc
10
+ from dash.html import Div
11
+
12
+ from .config import DEFAULT_ANNOTATION_CONFIG
13
+ from .custom_figure import CustomFigure
14
+
15
+ logger = logging.getLogger("dash_tooltip")
16
+
17
+
18
+ def _normalize_annotation_value(value: Any) -> Any:
19
+ if isinstance(value, float):
20
+ return format(value, ".15g")
21
+ return str(value)
22
+
23
+
24
+ def _annotation_exists(fig: CustomFigure, x: Any, y: Any, xref: str, yref: str) -> bool:
25
+ annotations = fig.layout.annotations or []
26
+ for annotation in annotations:
27
+ if (
28
+ _normalize_annotation_value(getattr(annotation, "x", None))
29
+ == _normalize_annotation_value(x)
30
+ and _normalize_annotation_value(getattr(annotation, "y", None))
31
+ == _normalize_annotation_value(y)
32
+ and getattr(annotation, "xref", None) == xref
33
+ and getattr(annotation, "yref", None) == yref
34
+ ):
35
+ return True
36
+ return False
37
+
38
+
39
+ def add_annotation_store(layout: Div, graph_id: Optional[str] = None) -> str:
40
+ """
41
+ Adds a dcc.Store component to the layout to store annotations for tooltips.
42
+
43
+ Args:
44
+ layout (dash.html.Div): The Dash app layout.
45
+ graph_id (str, optional): The ID of the graph component to which the store is linked.
46
+
47
+ Returns:
48
+ str: The ID of the added dcc.Store component.
49
+ """
50
+ store_id = "tooltip-annotations-to-remove"
51
+ if graph_id:
52
+ store_id += f"-{graph_id}"
53
+
54
+ if not any(
55
+ isinstance(child, dcc.Store) and child.id == store_id
56
+ for child in layout.children
57
+ ):
58
+ if isinstance(layout.children, list):
59
+ layout.children.append(dcc.Store(id=store_id))
60
+
61
+ return store_id
62
+
63
+
64
+ def _find_all_graph_ids(layout: Div) -> List[str]:
65
+ """Recursively search for all graph component IDs in the app layout."""
66
+ graph_ids = []
67
+
68
+ if isinstance(layout, dcc.Graph):
69
+ return [layout.id]
70
+
71
+ if hasattr(layout, "children"):
72
+ if isinstance(layout.children, list):
73
+ for child in layout.children:
74
+ graph_ids.extend(_find_all_graph_ids(child))
75
+ else:
76
+ graph_ids.extend(_find_all_graph_ids(layout.children))
77
+
78
+ return graph_ids
79
+
80
+
81
+ def extract_value_from_point(point: Dict[str, Any], key: str) -> Any:
82
+ """Extracts the value from the point dictionary using a dot notation key."""
83
+ try:
84
+ parts = key.split(".")
85
+ temp: Any = point
86
+ for part in parts:
87
+ match = re.match(r"(\w+)\[(\d+)\]", part)
88
+ if match:
89
+ name, index = match.groups()
90
+ index = int(index)
91
+ if temp and isinstance(temp, dict) and name in temp:
92
+ temp = temp.get(name, [])[index]
93
+ else:
94
+ return None
95
+ else:
96
+ if temp and isinstance(temp, dict):
97
+ temp = temp.get(part)
98
+ else:
99
+ return None
100
+ return temp
101
+ except Exception as e:
102
+ logger.error(f"Error extracting value with key {key}. Error: {e}")
103
+ return None
104
+
105
+
106
+ def truncate_json_arrays(json_str: str, limit: int) -> str:
107
+ """
108
+ Truncate arrays in a JSON string representation to a specified limit, both at top level and nested.
109
+
110
+ Parameters:
111
+ json_str (str): The JSON string representation to be processed.
112
+ limit (int): The maximum number of elements to keep in any array.
113
+
114
+ Returns:
115
+ str: The processed JSON string with arrays truncated.
116
+ """
117
+
118
+ def truncate_arrays(data: Any) -> Any:
119
+ """
120
+ Recursively truncate arrays in a data structure (dicts or lists).
121
+ """
122
+ if isinstance(data, list):
123
+ truncated_data = data[:limit]
124
+ if len(data) > limit:
125
+ truncated_data.append("[TRUNCATED]")
126
+ return [truncate_arrays(item) for item in truncated_data]
127
+ elif isinstance(data, dict):
128
+ return {key: truncate_arrays(value) for key, value in data.items()}
129
+ else:
130
+ return data
131
+
132
+ data = json.loads(json_str)
133
+ truncated_data = truncate_arrays(data)
134
+
135
+ return json.dumps(truncated_data, indent=4)
136
+
137
+
138
+ def deep_merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
139
+ """
140
+ Recursively merges two dictionaries.
141
+ Nested keys from dict2 will overwrite those in dict1.
142
+ """
143
+ for key, value in dict2.items():
144
+ if isinstance(value, dict) and key in dict1 and isinstance(dict1[key], dict):
145
+ dict1[key] = deep_merge_dicts(dict1[key], value)
146
+ else:
147
+ dict1[key] = value
148
+ return dict1
149
+
150
+
151
+ def get_axis_type(fig: go.Figure, axis: str) -> str:
152
+ """
153
+ Determines the type of the specified axis in a Plotly figure.
154
+
155
+ Parameters:
156
+ fig (go.Figure): The Plotly figure object.
157
+ axis (str): The axis identifier, e.g., 'x', 'y', 'x2', 'y2', etc.
158
+
159
+ Returns:
160
+ str: The type of the specified axis, e.g., 'linear' or 'log'.
161
+ """
162
+ # Check if the axis identifier has a number at the end
163
+ axis_number = axis[-1]
164
+ if axis_number.isnumeric():
165
+ axis_key = axis[:-1] + "axis" + axis_number
166
+ else:
167
+ axis_key = axis + "axis"
168
+
169
+ return fig.layout[axis_key].type
170
+
171
+
172
+ def _display_click_data(
173
+ clickData: Dict[str, Any],
174
+ figure: Union[CustomFigure, Dict[str, Any]], # Allow both go.Figure and dictionary
175
+ template: str,
176
+ config: Dict[Any, Any],
177
+ apply_log_fix: bool = True,
178
+ debug: bool = False,
179
+ ) -> CustomFigure:
180
+ """
181
+ Displays the tooltip on the graph when a data point is clicked.
182
+
183
+ Args:
184
+ clickData (Dict[str, Any]): The data from the click event.
185
+ figure (Union[CustomFigure, Dict[str, Any]]): The figure to update.
186
+ template (str): The template for the tooltip.
187
+ config (Dict[Any, Any]): The configuration for the tooltip.
188
+ apply_log_fix (bool, optional): Whether to apply the log axis fix. Defaults to True.
189
+ debug (bool, optional): Whether to enable debugging. Defaults to False.
190
+
191
+ Returns:
192
+ CustomFigure: The updated figure.
193
+ """
194
+ xaxis, yaxis = "x", "y" # Default values
195
+
196
+ if figure is None:
197
+ raise ValueError("The figure provided is None.")
198
+
199
+ # Check if figure is a dictionary
200
+ if isinstance(figure, dict):
201
+ # Extract data and layout from the figure dictionary
202
+ raw_data = figure.get("data", [])
203
+ layout = figure.get("layout", {})
204
+
205
+ # Convert dictionary representations of traces into actual trace objects
206
+ data = []
207
+ for trace in raw_data:
208
+ trace_type = trace.pop("type")
209
+ trace_class = getattr(go, trace_type.capitalize())
210
+ data.append(trace_class(**trace))
211
+
212
+ # Construct the go.Figure using data and layout
213
+ fig = CustomFigure(data=data, layout=layout)
214
+ elif isinstance(figure, CustomFigure):
215
+ fig = figure
216
+ else:
217
+ raise TypeError(
218
+ "The figure provided must be of type 'CustomFigure' or a dictionary."
219
+ )
220
+
221
+ fig.update_template(template)
222
+
223
+ merged_config = deep_merge_dicts(DEFAULT_ANNOTATION_CONFIG.copy(), config)
224
+
225
+ if not dash.callback_context:
226
+ raise dash.exceptions.PreventUpdate
227
+
228
+ if clickData:
229
+ point = clickData["points"][0]
230
+ x_val = point["x"]
231
+ y_val = point["y"]
232
+
233
+ try:
234
+ # Extract the clicked axis information from the curve data
235
+ if "xaxis" in fig["data"][point["curveNumber"]]:
236
+ xaxis = fig["data"][point["curveNumber"]]["xaxis"]
237
+ else:
238
+ xaxis = "x"
239
+
240
+ if "yaxis" in fig["data"][point["curveNumber"]]:
241
+ yaxis = fig["data"][point["curveNumber"]]["yaxis"]
242
+ else:
243
+ yaxis = "y"
244
+
245
+ if "meta" in fig["data"][point["curveNumber"]]:
246
+ point["meta"] = fig["data"][point["curveNumber"]]["meta"]
247
+
248
+ if "name" in fig["data"][point["curveNumber"]]:
249
+ point["name"] = fig["data"][point["curveNumber"]]["name"]
250
+
251
+ # If the x-axis is logarithmic, adjust `x_val`
252
+ if apply_log_fix and get_axis_type(fig, xaxis) == "log":
253
+ x_val = math.log10(x_val)
254
+
255
+ # If the y-axis is logarithmic, adjust `y_val`
256
+ if apply_log_fix and get_axis_type(fig, yaxis) == "log":
257
+ y_val = math.log10(y_val)
258
+
259
+ except KeyError as e:
260
+ logger.error(f"Error: {e}, key not found")
261
+ except Exception as e:
262
+ logger.error(f"An unexpected error occurred: {e}")
263
+
264
+ if debug:
265
+ logger.debug(
266
+ f"clickData: {truncate_json_arrays(json.dumps(clickData, indent=4), 2)}"
267
+ )
268
+ logger.debug(
269
+ f"figure: {truncate_json_arrays(json.dumps(fig, indent=4), 2)}"
270
+ )
271
+ logger.debug(
272
+ "Point data:\n%s", truncate_json_arrays(json.dumps(point, indent=4), 2)
273
+ )
274
+ logger.debug(
275
+ "Trace data:\n%s",
276
+ truncate_json_arrays(
277
+ json.dumps(fig["data"][point["curveNumber"]], indent=4), 2
278
+ ),
279
+ )
280
+
281
+ placeholders = re.findall(r"%{(.*?)}", fig.layout._tooltip_template)
282
+
283
+ template_data = {}
284
+ for placeholder in placeholders:
285
+ parts = placeholder.split(":")
286
+ var_name = parts[0]
287
+ format_spec = parts[1] if len(parts) > 1 else None
288
+
289
+ value = extract_value_from_point(point, var_name)
290
+ if value is not None:
291
+ if format_spec:
292
+ try:
293
+ # Applying the format specifier directly
294
+ template_data[placeholder] = f"{value:{format_spec}}"
295
+ except ValueError as e:
296
+ logger.error(
297
+ f"Error formatting value {value}, with format {format_spec}. Error: {e}"
298
+ )
299
+ template_data[placeholder] = str(value)
300
+ else:
301
+ template_data[placeholder] = str(value)
302
+
303
+ tooltip_template = fig.layout._tooltip_template
304
+ for placeholder, value in template_data.items():
305
+ tooltip_template = tooltip_template.replace(f"%{{{placeholder}}}", value)
306
+
307
+ if _annotation_exists(fig, x_val, y_val, xaxis, yaxis):
308
+ return fig
309
+
310
+ try:
311
+ fig.add_annotation(
312
+ x=x_val,
313
+ y=y_val,
314
+ xref=xaxis,
315
+ yref=yaxis,
316
+ text=tooltip_template,
317
+ **merged_config,
318
+ )
319
+ except ValueError as e:
320
+ logger.error(
321
+ f"Failed to add annotation due to invalid properties in {merged_config}. Error: {e}"
322
+ )
323
+ raise e
324
+ return fig
@@ -0,0 +1,301 @@
1
+ Metadata-Version: 2.4
2
+ Name: Dash_tooltip
3
+ Version: 0.5.0
4
+ Summary: A tooltip functionality for Dash.
5
+ Author: kb-
6
+ Project-URL: Homepage, https://github.com/kb-/Dash_tooltip
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.7
9
+ Classifier: Programming Language :: Python :: 3.8
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Requires-Python: >=3.7
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: dash>=2.13.0
21
+ Requires-Dist: plotly>=5.17.0
22
+ Dynamic: license-file
23
+
24
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/dash-tooltip)
25
+ [![CodeQL](https://github.com/kb-/Dash_tooltip/actions/workflows/codeql.yml/badge.svg?branch=main)](https://github.com/kb-/Dash_tooltip/actions/workflows/codeql.yml)
26
+ [![Downloads](https://static.pepy.tech/badge/dash_tooltip)](https://pepy.tech/project/dash_tooltip)
27
+ [![Pytest](https://github.com/kb-/Dash_tooltip/actions/workflows/Pytest.yml/badge.svg)](https://github.com/kb-/Dash_tooltip/actions/workflows/Pytest.yml)
28
+
29
+ # Dash Tooltip
30
+
31
+ A module to add interactive editable tooltips to your Dash applications. Inspired by `mplcursors` and Matlab's `datatip`.
32
+
33
+ ![newplot(6)](https://github.com/kb-/Dash_tooltip/assets/2260417/0d62008c-25f2-4128-aa31-6746b6b82248)
34
+
35
+ ## Installation
36
+
37
+ `pip install dash-tooltip`
38
+
39
+ ## Build And Publish
40
+
41
+ With the current `pyproject.toml`-based setup, use `uv` for local builds and publishing:
42
+
43
+ ```bash
44
+ # Build source distribution and wheel into dist/
45
+ uv build
46
+
47
+ # Install the built wheel locally
48
+ uv pip install dist/*.whl
49
+
50
+ # Publish to PyPI
51
+ uv publish
52
+ ```
53
+
54
+ ## Basic Usage
55
+
56
+ ```python
57
+ import numpy as np
58
+ import plotly.express as px
59
+ from dash import Dash, dcc, html
60
+ from dash.dependencies import Input, Output
61
+ from dash_tooltip import tooltip
62
+
63
+ # Sample Data
64
+ np.random.seed(20)
65
+ y1 = np.random.normal(0, 10, 50)
66
+ x1 = np.arange(0, 50)
67
+ fig1 = px.scatter(x=x1, y=y1)
68
+ fig1.update_layout(title_text="Editable Title", title_x=0.5)
69
+
70
+ app1 = Dash(__name__)
71
+
72
+ #makes graph items, including tooltips editable
73
+ app1.layout = html.Div([
74
+ dcc.Graph(
75
+ id='graph1',
76
+ figure=fig1,
77
+ config={
78
+ 'editable': True,
79
+ 'edits': {
80
+ 'shapePosition': True,
81
+ 'annotationPosition': True
82
+ }
83
+ }
84
+ )
85
+ ])
86
+
87
+ # Add the tooltip functionality to the app
88
+ tooltip(app1)
89
+ ```
90
+ Click on data points to add tooltips.
91
+ If `dcc.Graph` is configured editatble, tolltips:
92
+ - can be dragged around
93
+ - text can be edited on click
94
+ - can be deleted: click, delete text, enter. In some occasions a tooltip arrow may remain due to a Dash bug (clientside_callback not firing). In this cas, click near arrow end (mouse cursor changes to pointer), enter some text and repeat deletion and enter.
95
+
96
+
97
+ ## Advanced Usage
98
+
99
+ If you want to customize the tooltips, hover templates, and more:
100
+
101
+ ```python
102
+ import pandas as pd
103
+ import numpy as np
104
+ import plotly.express as px
105
+ from dash import Dash, dcc, html
106
+ from dash.dependencies import Input, Output
107
+ from dash_tooltip import tooltip
108
+
109
+ # Generate random time series data
110
+ date_rng = pd.date_range(start='2020-01-01', end='2020-12-31', freq='h')
111
+ ts1 = pd.Series(np.random.randn(len(date_rng)), index=date_rng, name='Time Series 1')
112
+ ts2 = pd.Series(np.random.randn(len(date_rng)), index=date_rng, name='Time Series 2')
113
+ df = pd.DataFrame({ts1.name: ts1, ts2.name: ts2})
114
+
115
+ # Define the hover and tooltip template
116
+ # name is only compatible with tooltip
117
+ template = "name:%{name}<br>META0: %{meta[0]}<br>META1: %{meta[1]}<br>x: %{x}<br>y: %{y:.2f}<br>pointNumber: %{pointNumber}<br>customdata0: %{customdata[0]}<br>customdata1: %{customdata[1]}"
118
+
119
+ # Create a line plot
120
+ fig10 = px.line(df, x=df.index, y=df.columns, title="Time Series Plot")
121
+
122
+ # Apply metadata and custom data to each trace
123
+ for i, trace in enumerate(fig10.data):
124
+ # Applying different metadata to each trace
125
+ trace.meta = [f"META{i}0", f"META{i}1"]
126
+
127
+ # Setting customdata for each point in the trace, for use in the hover template
128
+ trace.customdata = np.array([[f"Series {i+1}", f'Point {j+1}'] for j in range(len(df))])
129
+
130
+ # Setting the hover template
131
+ trace.hovertemplate = template
132
+
133
+ app10 = Dash(__name__)
134
+
135
+ app10.layout = html.Div([
136
+ dcc.Graph(
137
+ id="graph-id",
138
+ figure=fig10,
139
+ config={
140
+ 'editable': True,
141
+ 'edits': {
142
+ 'shapePosition': True,
143
+ 'annotationPosition': True
144
+ }
145
+ }
146
+ )
147
+ ])
148
+
149
+ tooltip(app10, graph_ids=["graph-id"], template=template, debug=True)
150
+ app10.run(port=8082)
151
+ ```
152
+
153
+ ## Tooltip Templates with Formatting
154
+
155
+ Tooltips can be formatted using templates similar to Plotly's hovertemplates. The tooltip template allows custom formatting and the inclusion of text and values.
156
+
157
+ For example, you can use a template like `"%{name}<br>%{meta[0]}<br>x: %{x:.2f}<br>y: %{y:.2f}"` to display the track `name`, `meta[0]` from a list of text data, plus `x` and `y` values with two decimal places. Note that `name` key is not available in the Plotly hover template, but is displayed by default.
158
+
159
+ Refer to [Plotly’s documentation on hover text and formatting](https://plotly.com/python/hover-text-and-formatting/) for more details on how to construct and customize your tooltip templates.
160
+
161
+ ## Custom Styling
162
+
163
+ ```python
164
+ custom_style = {
165
+ "font": {"size": 12, "color":"red"},
166
+ "arrowcolor": "red",
167
+ 'arrowsize': 5,
168
+ # ... any other customization
169
+ }
170
+ tooltip(app10, style=custom_style, graph_ids=["graph-id"], template=template, debug=True)
171
+ ```
172
+
173
+ For more examples, refer to the provided `dash_tooltip_demo.py` and check out [Plotly’s Text and Annotations documentation](https://plotly.com/python/text-and-annotations/#styling-and-coloring-annotations), which provides a wealth of information on customizing the appearance of annotations.
174
+ Refer to the [Plotly Annotation Reference](https://plotly.com/python/reference/layout/annotations/) for a comprehensive guide on available styling attributes and how to apply them.
175
+
176
+ ## Template updating
177
+
178
+ Tooltip content can be updated to match with selected data in a dynamic Dash app:
179
+ ```python
180
+ GRAPH_ID = "scatter-plot16a"
181
+
182
+ # Sample DataFrame with DatetimeIndex
183
+ date_range = pd.date_range(start="2025-01-01", periods=5)
184
+ df = pd.DataFrame(
185
+ {
186
+ "x": [1, 2, 3, 4, 5],
187
+ "y": [2, 4, 6, 8, 10],
188
+ "z": [3, 6, 9, 12, 15],
189
+ "a": [4, 8, 12, 16, 20],
190
+ "b": [5, 10, 15, 20, 25],
191
+ },
192
+ index=date_range,
193
+ )
194
+
195
+ # Initialize the Dash app
196
+ app16 = dash.Dash(__name__)
197
+
198
+ # Define the layout
199
+ app16.layout = html.Div(
200
+ [
201
+ html.Label("Select X and Y columns:"),
202
+ dcc.Dropdown(
203
+ id="x-column",
204
+ options=[{"label": col, "value": col} for col in df.columns],
205
+ placeholder="Select X axis data",
206
+ ),
207
+ dcc.Dropdown(
208
+ id="y-column",
209
+ options=[{"label": col, "value": col} for col in df.columns],
210
+ placeholder="Select Y axis data",
211
+ ),
212
+ dcc.Graph(
213
+ id=GRAPH_ID,
214
+ style={"width": "600px", "height": "600px"},
215
+ config={
216
+ "editable": True,
217
+ "edits": {"shapePosition": True, "annotationPosition": True},
218
+ },
219
+ ),
220
+ ]
221
+ )
222
+
223
+ # Create a tooltip instance
224
+ tooltip_instance16 = tooltip(app16, graph_ids=[GRAPH_ID])
225
+
226
+ # Define callback to update the scatter plot
227
+ @app16.callback(
228
+ Output(GRAPH_ID, "figure", allow_duplicate=True),
229
+ [Input("x-column", "value"), Input("y-column", "value")],
230
+ prevent_initial_call=True,
231
+ )
232
+ def update_scatter_plot(x_column, y_column):
233
+ if not x_column or not y_column:
234
+ raise PreventUpdate # Prevent update if either dropdown is not selected
235
+
236
+ non_selected_columns = [
237
+ col for col in df.columns if col not in [x_column, y_column]
238
+ ]
239
+ customdata = df[non_selected_columns].apply(
240
+ lambda row: "<br>".join(
241
+ f"{col}: {val}" for col, val in zip(non_selected_columns, row)
242
+ ),
243
+ axis=1,
244
+ )
245
+ # gives (depending on selected entries):
246
+ # 2022-01-01 x: 1<br>z: 3<br>b: 5
247
+ # 2022-01-02 x: 2<br>z: 6<br>b: 10
248
+ # ...
249
+
250
+ # New template, to match selected data entries
251
+ template = (
252
+ "<b>Date</b>: %{customdata}<br>"
253
+ + f"<b>{x_column}: %{{x}}<br>"
254
+ + f"{y_column}: %{{y}}</b><br>"
255
+ )
256
+ # gives (depending on selected entries):
257
+ # <b>Date</b>: %{customdata}<br><b>x: %{x}<br><b>a</b>: %{y}<br>
258
+
259
+ # Update template for new tooltips
260
+ tooltip_instance16.update_template(graph_id=GRAPH_ID, template=template)
261
+
262
+ trace = go.Scatter(
263
+ x=df[x_column],
264
+ y=df[y_column],
265
+ mode="markers",
266
+ marker=dict(color="blue"),
267
+ customdata=df.index.strftime("%Y-%m-%d %H:%M:%S") + "<br>" + customdata,
268
+ # Include date and time with other data
269
+ hovertemplate=template,
270
+ )
271
+ layout = go.Layout(
272
+ title="Scatter Plot",
273
+ xaxis=dict(title=x_column),
274
+ yaxis=dict(title=y_column),
275
+ hovermode="closest",
276
+ height=800,
277
+ width=800,
278
+ )
279
+ return {"data": [trace], "layout": layout}
280
+
281
+
282
+ # Run the app
283
+ if __name__ == "__main__":
284
+ app16.run(debug=False, port=8196)
285
+ ```
286
+
287
+ ## Handling Log Axes
288
+
289
+ Due to a long-standing bug in Plotly (see [Plotly Issue #2580](https://github.com/plotly/plotly.py/issues/2580)), annotations (`fig.add_annotation`) may not be placed correctly on log-scaled axes. The `dash_tooltip` module provides an option to automatically correct the tooltip placement on log-scaled axes via the `apply_log_fix` argument in the `tooltip` function. By default, `apply_log_fix` is set to `True` to enable the fix.
290
+
291
+ ## Debugging
292
+
293
+ If you encounter any issues or unexpected behaviors, enable the debug mode by setting the `debug` argument of the `tooltip` function to `True`. The log outputs will be written to `dash_app.log` in the directory where your script or application is located.
294
+
295
+ ## License
296
+
297
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
298
+
299
+ ## Acknowledgements
300
+
301
+ - Inspired by `mplcursors` and Matlab's `datatip`.
@@ -0,0 +1,10 @@
1
+ dash_tooltip/__init__.py,sha256=lMISp--speJuMSqwxttnjPrQl3NSAqifKqkRF0WUMB4,10298
2
+ dash_tooltip/_version.py,sha256=VgJxLFMR_D2Bdx1B0gV0fBHBM-yHMFQUDPjx3w1PU_M,586
3
+ dash_tooltip/config.py,sha256=FEGpY4bxCSCv_8HSIyPl0BrMpUvxrxNLTXmAu25rV2c,842
4
+ dash_tooltip/custom_figure.py,sha256=a8hWSYnLs66VX6i8FyKqWKvcHD6a75vihcG_w1BJwBE,343
5
+ dash_tooltip/utils.py,sha256=BnrOJ0_naXmuUKEVzoTRHrPqm7bbw1kpyZ59AbXKE5U,11262
6
+ dash_tooltip-0.5.0.dist-info/licenses/LICENSE,sha256=iprCc-jRiuJNs3MnFMOct-tWW_D5bBG1RASo-wQNTQk,1081
7
+ dash_tooltip-0.5.0.dist-info/METADATA,sha256=7NvNM6uXpyN25BE3gZbga5xLVgYO7FMPQTUnBfCHxMA,10717
8
+ dash_tooltip-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ dash_tooltip-0.5.0.dist-info/top_level.txt,sha256=W8gDLeFCRYy1nSEeg_k2AwGM8Zm2vi28QkWZlVpinck,13
10
+ dash_tooltip-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 kb-
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ dash_tooltip