plotly.py 8.7 KB

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