plotly.py 8.4 KB

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