plotly.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from typing import Dict, Union
  2. import plotly.graph_objects as go
  3. from ..dependencies import js_dependencies, register_component
  4. from ..element import Element
  5. register_component('plotly', __file__, 'plotly.vue', [], ['lib/plotly.min.js'])
  6. class Plotly(Element):
  7. def __init__(self, figure: Union[Dict, go.Figure]) -> None:
  8. """Plotly Element
  9. Renders a Plotly chart.
  10. There are two ways to pass a Plotly figure for rendering, see parameter `figure`:
  11. * Pass a `go.Figure` object, see https://plotly.com/python/
  12. * Pass a Python `dict` object with keys `data`, `layout`, `config` (optional), see https://plotly.com/javascript/
  13. For best performance, use the declarative `dict` approach for creating a Plotly chart.
  14. :param figure: Plotly figure to be rendered. Can be either a `go.Figure` instance, or
  15. a `dict` object with keys `data`, `layout`, `config` (optional).
  16. """
  17. super().__init__('plotly')
  18. self.figure = figure
  19. self._props['lib'] = [d.import_path for d in js_dependencies.values() if d.path.name == 'plotly.min.js'][0]
  20. self.update()
  21. def update_figure(self, figure: Union[Dict, go.Figure]):
  22. """Overrides figure instance of this Plotly chart and updates chart on client side."""
  23. self.figure = figure
  24. self.update()
  25. def update(self) -> None:
  26. super().update()
  27. self._props['options'] = self._get_figure_json()
  28. self.run_method('update', self._props['options'])
  29. def _get_figure_json(self) -> Dict:
  30. if isinstance(self.figure, go.Figure):
  31. # convert go.Figure to dict object which is directly JSON serializable
  32. # orjson supports numpy array serialization
  33. return self.figure.to_plotly_json()
  34. if isinstance(self.figure, dict):
  35. # already a dict object with keys: data, layout, config (optional)
  36. return self.figure
  37. raise ValueError(f'Plotly figure is of unknown type "{self.figure.__class__.__name__}".')