plotly.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """Component for displaying a plotly graph."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Tuple, Union
  4. from typing_extensions import TypedDict, TypeVar
  5. from reflex.components.component import Component, NoSSRComponent
  6. from reflex.components.core.cond import color_mode_cond
  7. from reflex.event import EventHandler, no_args_event_spec
  8. from reflex.utils import console
  9. from reflex.vars.base import LiteralVar, Var
  10. try:
  11. from plotly.graph_objects import Figure, layout
  12. Template = layout.Template
  13. except ImportError:
  14. console.warn("Plotly is not installed. Please run `pip install plotly`.")
  15. Figure = Any # type: ignore
  16. Template = Any # type: ignore
  17. def _event_points_data_signature(e0: Var) -> Tuple[Var[List[Point]]]:
  18. """For plotly events with event data containing a point array.
  19. Args:
  20. e0: The event data.
  21. Returns:
  22. The event data and the extracted points.
  23. """
  24. return (Var(_js_expr=f"extractPoints({e0}?.points)"),)
  25. T = TypeVar("T")
  26. ItemOrList = Union[T, List[T]]
  27. class BBox(TypedDict):
  28. """Bounding box for a point in a plotly graph."""
  29. x0: Union[float, int, None]
  30. x1: Union[float, int, None]
  31. y0: Union[float, int, None]
  32. y1: Union[float, int, None]
  33. z0: Union[float, int, None]
  34. z1: Union[float, int, None]
  35. class Point(TypedDict):
  36. """A point in a plotly graph."""
  37. x: Union[float, int, None]
  38. y: Union[float, int, None]
  39. z: Union[float, int, None]
  40. lat: Union[float, int, None]
  41. lon: Union[float, int, None]
  42. curveNumber: Union[int, None]
  43. pointNumber: Union[int, None]
  44. pointNumbers: Union[List[int], None]
  45. pointIndex: Union[int, None]
  46. markerColor: Union[
  47. ItemOrList[
  48. ItemOrList[
  49. Union[
  50. float,
  51. int,
  52. str,
  53. None,
  54. ]
  55. ]
  56. ],
  57. None,
  58. ]
  59. markerSize: Union[
  60. ItemOrList[
  61. ItemOrList[
  62. Union[
  63. float,
  64. int,
  65. None,
  66. ]
  67. ]
  68. ],
  69. None,
  70. ]
  71. bbox: Union[BBox, None]
  72. class Plotly(NoSSRComponent):
  73. """Display a plotly graph."""
  74. library = "react-plotly.js@2.6.0"
  75. lib_dependencies: List[str] = ["plotly.js@2.35.2"]
  76. tag = "Plot"
  77. is_default = True
  78. # The figure to display. This can be a plotly figure or a plotly data json.
  79. data: Var[Figure] # type: ignore
  80. # The layout of the graph.
  81. layout: Var[Dict]
  82. # The template for visual appearance of the graph.
  83. template: Var[Template] # type: ignore
  84. # The config of the graph.
  85. config: Var[Dict]
  86. # If true, the graph will resize when the window is resized.
  87. use_resize_handler: Var[bool] = LiteralVar.create(True)
  88. # Fired after the plot is redrawn.
  89. on_after_plot: EventHandler[no_args_event_spec]
  90. # Fired after the plot was animated.
  91. on_animated: EventHandler[no_args_event_spec]
  92. # Fired while animating a single frame (does not currently pass data through).
  93. on_animating_frame: EventHandler[no_args_event_spec]
  94. # Fired when an animation is interrupted (to start a new animation for example).
  95. on_animation_interrupted: EventHandler[no_args_event_spec]
  96. # Fired when the plot is responsively sized.
  97. on_autosize: EventHandler[no_args_event_spec]
  98. # Fired whenever mouse moves over a plot.
  99. on_before_hover: EventHandler[no_args_event_spec]
  100. # Fired when a plotly UI button is clicked.
  101. on_button_clicked: EventHandler[no_args_event_spec]
  102. # Fired when the plot is clicked.
  103. on_click: EventHandler[_event_points_data_signature]
  104. # Fired when a selection is cleared (via double click).
  105. on_deselect: EventHandler[no_args_event_spec]
  106. # Fired when the plot is double clicked.
  107. on_double_click: EventHandler[no_args_event_spec]
  108. # Fired when a plot element is hovered over.
  109. on_hover: EventHandler[_event_points_data_signature]
  110. # Fired after the plot is layed out (zoom, pan, etc).
  111. on_relayout: EventHandler[no_args_event_spec]
  112. # Fired while the plot is being layed out.
  113. on_relayouting: EventHandler[no_args_event_spec]
  114. # Fired after the plot style is changed.
  115. on_restyle: EventHandler[no_args_event_spec]
  116. # Fired after the plot is redrawn.
  117. on_redraw: EventHandler[no_args_event_spec]
  118. # Fired after selecting plot elements.
  119. on_selected: EventHandler[_event_points_data_signature]
  120. # Fired while dragging a selection.
  121. on_selecting: EventHandler[_event_points_data_signature]
  122. # Fired while an animation is occuring.
  123. on_transitioning: EventHandler[no_args_event_spec]
  124. # Fired when a transition is stopped early.
  125. on_transition_interrupted: EventHandler[no_args_event_spec]
  126. # Fired when a hovered element is no longer hovered.
  127. on_unhover: EventHandler[_event_points_data_signature]
  128. def add_imports(self) -> dict[str, str]:
  129. """Add imports for the plotly component.
  130. Returns:
  131. The imports for the plotly component.
  132. """
  133. return {
  134. # For merging plotly data/layout/templates.
  135. "mergician@v2.0.2": "mergician"
  136. }
  137. def add_custom_code(self) -> list[str]:
  138. """Add custom codes for processing the plotly points data.
  139. Returns:
  140. Custom code snippets for the module level.
  141. """
  142. return [
  143. "const removeUndefined = (obj) => {Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]); return obj}",
  144. """
  145. const extractPoints = (points) => {
  146. if (!points) return [];
  147. return points.map(point => {
  148. const bbox = point.bbox ? removeUndefined({
  149. x0: point.bbox.x0,
  150. x1: point.bbox.x1,
  151. y0: point.bbox.y0,
  152. y1: point.bbox.y1,
  153. z0: point.bbox.y0,
  154. z1: point.bbox.y1,
  155. }) : undefined;
  156. return removeUndefined({
  157. x: point.x,
  158. y: point.y,
  159. z: point.z,
  160. lat: point.lat,
  161. lon: point.lon,
  162. curveNumber: point.curveNumber,
  163. pointNumber: point.pointNumber,
  164. pointNumbers: point.pointNumbers,
  165. pointIndex: point.pointIndex,
  166. markerColor: point['marker.color'],
  167. markerSize: point['marker.size'],
  168. bbox: bbox,
  169. })
  170. })
  171. }
  172. """,
  173. ]
  174. @classmethod
  175. def create(cls, *children, **props) -> Component:
  176. """Create the Plotly component.
  177. Args:
  178. *children: The children of the component.
  179. **props: The properties of the component.
  180. Returns:
  181. The Plotly component.
  182. """
  183. from plotly.io import templates
  184. responsive_template = color_mode_cond(
  185. light=LiteralVar.create(templates["plotly"]),
  186. dark=LiteralVar.create(templates["plotly_dark"]),
  187. )
  188. if isinstance(responsive_template, Var):
  189. # Mark the conditional Var as a Template to avoid type mismatch
  190. responsive_template = responsive_template.to(Template)
  191. props.setdefault("template", responsive_template)
  192. return super().create(*children, **props)
  193. def _exclude_props(self) -> set[str]:
  194. # These props are handled specially in the _render function
  195. return {"data", "layout", "template"}
  196. def _render(self):
  197. tag = super()._render()
  198. figure = self.data.to(dict) if self.data is not None else Var.create({})
  199. merge_dicts = [] # Data will be merged and spread from these dict Vars
  200. if self.layout is not None:
  201. # Why is this not a literal dict? Great question... it didn't work
  202. # reliably because of how _var_name_unwrapped strips the outer curly
  203. # brackets if any of the contained Vars depend on state.
  204. layout_dict = LiteralVar.create({"layout": self.layout})
  205. merge_dicts.append(layout_dict)
  206. if self.template is not None:
  207. template_dict = LiteralVar.create({"layout": {"template": self.template}})
  208. merge_dicts.append(template_dict._without_data())
  209. if merge_dicts:
  210. tag.special_props.append(
  211. # Merge all dictionaries and spread the result over props.
  212. Var(
  213. _js_expr=f"{{...mergician({str(figure)},"
  214. f"{','.join(str(md) for md in merge_dicts)})}}",
  215. ),
  216. )
  217. else:
  218. # Spread the figure dict over props, nothing to merge.
  219. tag.special_props.append(Var(_js_expr=f"{{...{str(figure)}}}"))
  220. return tag