plotly.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """Component for displaying a plotly graph."""
  2. from typing import Dict, Union
  3. from plotly.graph_objects import Figure
  4. from plotly.io import to_json
  5. from pynecone.components.component import Component
  6. from pynecone.components.tags import Tag
  7. from pynecone.var import Var
  8. class PlotlyLib(Component):
  9. """A component that wraps a plotly lib."""
  10. library = "react-plotly.js"
  11. class Plotly(PlotlyLib):
  12. """Display a plotly graph."""
  13. tag = "Plot"
  14. # The figure to display. This can be a plotly figure or a plotly data json.
  15. data: Var[Figure]
  16. # The layout of the graph.
  17. layout: Var[Dict]
  18. # The width of the graph.
  19. width: Var[str]
  20. # The height of the graph.
  21. height: Var[str]
  22. def _get_imports(self):
  23. return {}
  24. def _get_custom_code(self) -> str:
  25. return """import dynamic from 'next/dynamic'
  26. const Plot = dynamic(() => import('react-plotly.js'), { ssr: false });
  27. """
  28. def _render(self) -> Tag:
  29. if (
  30. isinstance(self.data, Figure)
  31. and self.layout is None
  32. and self.width is not None
  33. ):
  34. layout = Var.create({"width": self.width, "height": self.height})
  35. assert layout is not None
  36. self.layout = layout
  37. return super()._render()