plotly.py 2.2 KB

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