plotly.py 1.2 KB

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