plotly.py 8.5 KB

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