plotly.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from typing import 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. There are two ways to pass a Plotly figure for rendering, see parameter `figure`:
  10. * Pass a `go.Figure` object, see https://plotly.com/python/
  11. * Pass a Python `dict` object with keys `data`, `layout`, `config` (optional), see https://plotly.com/javascript/
  12. For best performance, use the declarative `dict` approach for creating a Plotly chart.
  13. :param figure: Plotly figure to be rendered. Can be either a `go.Figure` instance, or
  14. a `dict` object with keys `data`, `layout`, `config` (optional).
  15. """
  16. super().__init__('plotly')
  17. self.figure = figure
  18. self._props['lib'] = [d.import_path for d in js_dependencies.values() if d.path.name == 'plotly.min.js'][0]
  19. self.update()
  20. def update_figure(self, figure: Union[dict, go.Figure]):
  21. """
  22. Overrides figure instance of this Plotly chart and updates chart on client side.
  23. """
  24. self.figure = figure
  25. self.update()
  26. def update(self) -> None:
  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__}'.")