plotly.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Component for displaying a plotly graph."""
  2. import json
  3. from typing import Any, Dict, List
  4. from reflex.components.component import NoSSRComponent
  5. from reflex.utils.serializers import serializer
  6. from reflex.vars import Var
  7. try:
  8. from plotly.graph_objects import Figure
  9. except ImportError:
  10. Figure = Any
  11. class PlotlyLib(NoSSRComponent):
  12. """A component that wraps a plotly lib."""
  13. library = "react-plotly.js@^2.6.0"
  14. lib_dependencies: List[str] = ["plotly.js@^2.22.0"]
  15. class Plotly(PlotlyLib):
  16. """Display a plotly graph."""
  17. tag = "Plot"
  18. is_default = True
  19. # The figure to display. This can be a plotly figure or a plotly data json.
  20. data: Var[Figure]
  21. # The layout of the graph.
  22. layout: Var[Dict]
  23. # The width of the graph.
  24. width: Var[str]
  25. # The height of the graph.
  26. height: Var[str]
  27. # If true, the graph will resize when the window is resized.
  28. use_resize_handler: Var[bool]
  29. try:
  30. from plotly.graph_objects import Figure
  31. from plotly.io import to_json
  32. @serializer
  33. def serialize_figure(figure: Figure) -> list:
  34. """Serialize a plotly figure.
  35. Args:
  36. figure: The figure to serialize.
  37. Returns:
  38. The serialized figure.
  39. """
  40. return json.loads(str(to_json(figure)))["data"]
  41. except ImportError:
  42. pass