1
0

plotly.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Component for displaying a plotly graph."""
  2. from typing import Any, Dict, List
  3. from reflex.components.component import NoSSRComponent
  4. from reflex.vars import Var
  5. try:
  6. from plotly.graph_objects import Figure
  7. except ImportError:
  8. Figure = Any # type: ignore
  9. class PlotlyLib(NoSSRComponent):
  10. """A component that wraps a plotly lib."""
  11. library = "react-plotly.js@2.6.0"
  12. lib_dependencies: List[str] = ["plotly.js@2.22.0"]
  13. class Plotly(PlotlyLib):
  14. """Display a plotly graph."""
  15. tag = "Plot"
  16. is_default = True
  17. # The figure to display. This can be a plotly figure or a plotly data json.
  18. data: Var[Figure]
  19. # The layout of the graph.
  20. layout: Var[Dict]
  21. # The config of the graph.
  22. config: Var[Dict]
  23. # If true, the graph will resize when the window is resized.
  24. use_resize_handler: Var[bool]
  25. def _render(self):
  26. tag = super()._render()
  27. figure = self.data.to(dict)
  28. if self.layout is None:
  29. tag.remove_props("data", "layout")
  30. tag.special_props.add(
  31. Var.create_safe(f"{{...{figure._var_name_unwrapped}}}")
  32. )
  33. else:
  34. tag.add_props(data=figure["data"])
  35. return tag