plotly.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from __future__ import annotations
  2. from typing import Dict, Union
  3. from .. import globals
  4. from ..element import Element
  5. try:
  6. import plotly.graph_objects as go
  7. globals.optional_features.add('plotly')
  8. except ImportError:
  9. pass
  10. class Plotly(Element, component='plotly.vue', libraries=['lib/plotly/plotly.min.js']):
  11. def __init__(self, figure: Union[Dict, go.Figure]) -> None:
  12. """Plotly Element
  13. Renders a Plotly chart.
  14. There are two ways to pass a Plotly figure for rendering, see parameter `figure`:
  15. * Pass a `go.Figure` object, see https://plotly.com/python/
  16. * Pass a Python `dict` object with keys `data`, `layout`, `config` (optional), see https://plotly.com/javascript/
  17. For best performance, use the declarative `dict` approach for creating a Plotly chart.
  18. :param figure: Plotly figure to be rendered. Can be either a `go.Figure` instance, or
  19. a `dict` object with keys `data`, `layout`, `config` (optional).
  20. """
  21. if not 'plotly' in globals.optional_features:
  22. raise ImportError('Plotly is not installed. Please run "pip install nicegui[plotly]".')
  23. super().__init__()
  24. self.figure = figure
  25. self.update()
  26. def update_figure(self, figure: Union[Dict, go.Figure]):
  27. """Overrides figure instance of this Plotly chart and updates chart on client side."""
  28. self.figure = figure
  29. self.update()
  30. def update(self) -> None:
  31. self._props['options'] = self._get_figure_json()
  32. super().update()
  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__}".')