Code reference
Build animated charts in Jupyter Notebook
and similar environments with a simple Python
syntax.
ipyvizzu
package consists of the following main modules:
ipyvizzu
package imports the following objects in __init__.py
:
- Chart
- Data
- Config
- Style
- Keyframe
- Snapshot
- Animation
- AbstractAnimation
- PlainAnimation
- AnimationMerger
- AnimationControl
- InferType
- NumpyArrayConverter
- PandasDataFrameConverter
- Animate
- Feature
- Store
- EventOn
- EventOff
- Log
- Method
- EventHandler
- RawJavaScript
- RawJavaScriptEncoder
- ChartProperty
- DisplayTarget
- DisplayTemplate
ipyvizzu.Chart
A class for representing a wrapper over Vizzu chart.
Source code in src/ipyvizzu/chart.py
class Chart:
"""A class for representing a wrapper over Vizzu chart."""
# pylint: disable=too-many-instance-attributes
VIZZU: str = VIZZU_URL
"""A variable for storing the default url of the `vizzu` package."""
def __init__(
self,
vizzu: str = VIZZU,
width: str = "800px",
height: str = "480px",
display: Union[DisplayTarget, str] = DisplayTarget.ACTUAL,
):
"""
Chart constructor.
Args:
vizzu: The url of Vizzu JavaScript package.
width: The width of the chart.
height: The height of the chart.
display: The display behaviour of the chart.
"""
self._chart_id: str = uuid.uuid4().hex[:7]
self._vizzu: str = vizzu
self._width: str = width
self._height: str = height
self._display_target: DisplayTarget = DisplayTarget(display)
self._calls: List[str] = []
self._last_anim: Optional[str] = None
self._showed: bool = False
self._initialized: bool = False
self._analytics: bool = True
self._scroll_into_view: bool = False
@staticmethod
def _register_events() -> None:
ipy = get_ipython()
if ipy is not None:
ipy.events.register("pre_run_cell", Chart._register_pre_run_cell)
@staticmethod
def _register_pre_run_cell(
*args, **kwargs # pylint: disable=unused-argument
) -> None:
display_javascript(DisplayTemplate.CLEAR_INHIBITSCROLL, raw=True)
@property
def analytics(self) -> bool:
"""
A property for enabling/disabling the usage statistics feature.
The usage statistics feature allows aggregate usage data collection
using Plausible's algorithm.
Enabling this feature helps us follow the progress and overall trends of our library,
allowing us to focus our resources effectively and better serve our users.
We do not track, collect, or store any personal data or personally identifiable information.
All data is isolated to a single day, a single site, and a single device only.
Please note that even when this feature is enabled,
publishing anything made with `ipyvizzu` remains GDPR compatible.
Returns:
The value of the property (default `True`).
"""
return self._analytics
@analytics.setter
def analytics(self, analytics: Optional[bool]) -> None:
self._analytics = bool(analytics)
if self._initialized:
self._display_analytics()
@property
def scroll_into_view(self) -> bool:
"""
A property for turning on/off the scroll into view feature.
Returns:
The value of the property (default `False`).
"""
return self._scroll_into_view
@scroll_into_view.setter
def scroll_into_view(self, scroll_into_view: Optional[bool]) -> None:
self._scroll_into_view = bool(scroll_into_view)
@property
def control(self) -> AnimationControl:
"""
A property for returning a control object of the last animation.
Raises:
AssertionError: If called before any animation plays.
Returns:
The control object of the last animation.
"""
assert self._last_anim, "must be used after an animation."
return AnimationControl(self._chart_id, self._last_anim, self._display)
def initializing(self) -> None:
"""A method for initializing the chart."""
if not self._initialized:
self._initialized = True
self._display_ipyvizzujs()
self._display_analytics()
if self._display_target != DisplayTarget.MANUAL:
Chart._register_events()
self._display_chart()
def _display_ipyvizzujs(self) -> None:
ipyvizzurawjs = pkgutil.get_data(__name__, "templates/ipyvizzu.js")
ipyvizzujs = ipyvizzurawjs.decode("utf-8").replace( # type: ignore
"'__version__'", f"'{__version__}'"
)
self._display(DisplayTemplate.IPYVIZZUJS.format(ipyvizzujs=ipyvizzujs))
def _display_analytics(self) -> None:
self._display(
DisplayTemplate.CHANGE_ANALYTICS_TO.format(
analytics=str(self._analytics).lower()
)
)
def _display_chart(self) -> None:
self._display(
DisplayTemplate.INIT.format(
chart_id=self._chart_id,
vizzu=self._vizzu,
div_width=self._width,
div_height=self._height,
)
)
def animate(
self,
*animations: AbstractAnimation,
**options: Optional[Union[str, int, float, dict]],
) -> None:
"""
A method for changing the state of the chart.
Args:
*animations:
List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
**options: Dictionary of animation options for example `duration=1`.
For information on all available animation options see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).
Raises:
ValueError: If `animations` is not set.
Example:
Reset the chart styles:
chart.animate(Style(None))
""" # pylint: disable=line-too-long
if not animations:
raise ValueError("No animation was set.")
animation = AnimationMerger.merge_animations(animations)
animate = Animate(animation, options)
self._last_anim = uuid.uuid4().hex[:7]
self._display(
DisplayTemplate.ANIMATE.format(
display_target=self._display_target.value,
chart_id=self._chart_id,
anim_id=self._last_anim,
scroll=str(self._scroll_into_view).lower(),
**animate.dump(),
)
)
def feature(self, name: str, enabled: bool) -> None:
"""
A method for turning on/off features of the chart.
Args:
name:
The name of the chart feature.
For information on all available features see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/modules/vizzu/#feature).
enabled: The new state of the chart feature.
Example:
Turn on `tooltip` of the chart:
chart.feature("tooltip", True)
""" # pylint: disable=line-too-long
self._display(
DisplayTemplate.FEATURE.format(
chart_id=self._chart_id,
**Feature(name, enabled).dump(),
)
)
def plugin(
self,
plugin: str,
options: Optional[dict] = None,
name: str = "default",
enabled: bool = True,
) -> None:
"""
A method for register/unregister plugins of the chart.
Args:
plugin: The package name or the url of the plugin.
options: The plugin constructor options.
name: The name of the plugin (default `default`).
enabled: The state of the plugin (default `True`).
"""
self._display(
DisplayTemplate.PLUGIN.format(
chart_id=self._chart_id,
**Plugin(plugin, options, name, enabled).dump(),
)
)
def store(self) -> Snapshot:
"""
A method for saving and storing the actual state of the chart.
Returns:
A Snapshot object wich stores the actual state of the chart.
Example:
Save and restore the actual state of the chart:
snapshot = chart.store()
...
chart.animate(snapshot)
"""
snapshot_id = uuid.uuid4().hex[:7]
self._display(
DisplayTemplate.STORE.format(
chart_id=self._chart_id, **Store(snapshot_id).dump()
)
)
return Snapshot(snapshot_id)
def on( # pylint: disable=invalid-name
self, event: str, handler: str
) -> EventHandler:
"""
A method for creating and turning on an event handler.
Args:
event:
The type of the event.
For information on all available events see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/modules/events/).
handler: The JavaScript method of the event.
Returns:
The turned on event handler object.
Example:
Turn on an event handler which prints an alert message
when someone clicks on the chart:
handler = chart.on("click", "alert(JSON.stringify(event.data));")
""" # pylint: disable=line-too-long
event_handler = EventHandler(event, handler)
self._display(
DisplayTemplate.SET_EVENT.format(
chart_id=self._chart_id,
**EventOn(event_handler).dump(),
)
)
return event_handler
def off(self, event_handler: EventHandler) -> None:
"""
A method for turning off an event handler.
Args:
event_handler: A previously created event handler object.
Example:
Turn off a previously created event handler:
chart.off(handler)
"""
self._display(
DisplayTemplate.CLEAR_EVENT.format(
chart_id=self._chart_id,
**EventOff(event_handler).dump(),
)
)
def log(self, chart_property: ChartProperty) -> None:
"""
A method for printing chart properties to the browser console.
Args:
chart_property:
A chart property such as
[CONFIG][ipyvizzu.template.ChartProperty] and
[STYLE][ipyvizzu.template.ChartProperty].
Example:
Log the actual style of the chart to the browser console:
chart.log(ChartProperty.STYLE)
"""
self._display(
DisplayTemplate.LOG.format(
chart_id=self._chart_id, **Log(chart_property).dump()
)
)
def _repr_html_(self) -> str:
assert (
self._display_target == DisplayTarget.MANUAL
), "chart._repr_html_() can be used with display=DisplayTarget.MANUAL only"
assert not self._showed, "cannot be used after chart displayed."
self._showed = True
if not self._initialized:
return ""
html_id = uuid.uuid4().hex[:7]
script = (
self._calls[0]
+ "\n"
+ "\n".join(self._calls[1:]).replace(
"element", f'document.getElementById("{html_id}")'
)
)
return f'<div id="{html_id}"><script>{script}</script></div>'
def show(self) -> None:
"""
A method for displaying the assembled JavaScript code.
Raises:
AssertionError: If [display][ipyvizzu.Chart.__init__]
is not [DisplayTarget.MANUAL][ipyvizzu.template.DisplayTarget].
AssertionError: If chart already has been displayed.
"""
assert (
self._display_target == DisplayTarget.MANUAL
), "chart.show() can be used with display=DisplayTarget.MANUAL only"
assert not self._showed, "cannot be used after chart displayed"
display_javascript(
"\n".join(self._calls),
raw=True,
)
self._showed = True
def _display(self, javascript: str) -> None:
if not self._initialized:
self.initializing()
if self._display_target != DisplayTarget.MANUAL:
display_javascript(
javascript,
raw=True,
)
else:
assert not self._showed, "cannot be used after chart displayed"
self._calls.append(javascript)
VIZZU: str = VIZZU_URL
class-attribute
instance-attribute
A variable for storing the default url of the vizzu
package.
analytics: bool
property
writable
A property for enabling/disabling the usage statistics feature.
The usage statistics feature allows aggregate usage data collection using Plausible's algorithm. Enabling this feature helps us follow the progress and overall trends of our library, allowing us to focus our resources effectively and better serve our users.
We do not track, collect, or store any personal data or personally identifiable information. All data is isolated to a single day, a single site, and a single device only.
Please note that even when this feature is enabled,
publishing anything made with ipyvizzu
remains GDPR compatible.
Returns:
Type | Description |
---|---|
bool
|
The value of the property (default |
scroll_into_view: bool
property
writable
A property for turning on/off the scroll into view feature.
Returns:
Type | Description |
---|---|
bool
|
The value of the property (default |
control: AnimationControl
property
A property for returning a control object of the last animation.
Raises:
Type | Description |
---|---|
AssertionError
|
If called before any animation plays. |
Returns:
Type | Description |
---|---|
AnimationControl
|
The control object of the last animation. |
__init__(vizzu=VIZZU, width='800px', height='480px', display=DisplayTarget.ACTUAL)
Chart constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vizzu |
str
|
The url of Vizzu JavaScript package. |
VIZZU
|
width |
str
|
The width of the chart. |
'800px'
|
height |
str
|
The height of the chart. |
'480px'
|
display |
Union[DisplayTarget, str]
|
The display behaviour of the chart. |
ACTUAL
|
Source code in src/ipyvizzu/chart.py
def __init__(
self,
vizzu: str = VIZZU,
width: str = "800px",
height: str = "480px",
display: Union[DisplayTarget, str] = DisplayTarget.ACTUAL,
):
"""
Chart constructor.
Args:
vizzu: The url of Vizzu JavaScript package.
width: The width of the chart.
height: The height of the chart.
display: The display behaviour of the chart.
"""
self._chart_id: str = uuid.uuid4().hex[:7]
self._vizzu: str = vizzu
self._width: str = width
self._height: str = height
self._display_target: DisplayTarget = DisplayTarget(display)
self._calls: List[str] = []
self._last_anim: Optional[str] = None
self._showed: bool = False
self._initialized: bool = False
self._analytics: bool = True
self._scroll_into_view: bool = False
initializing()
A method for initializing the chart.
Source code in src/ipyvizzu/chart.py
def initializing(self) -> None:
"""A method for initializing the chart."""
if not self._initialized:
self._initialized = True
self._display_ipyvizzujs()
self._display_analytics()
if self._display_target != DisplayTarget.MANUAL:
Chart._register_events()
self._display_chart()
animate(*animations, **options)
A method for changing the state of the chart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*animations |
AbstractAnimation
|
()
|
|
**options |
Optional[Union[str, int, float, dict]]
|
Dictionary of animation options for example |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
Example
Reset the chart styles:
chart.animate(Style(None))
Source code in src/ipyvizzu/chart.py
def animate(
self,
*animations: AbstractAnimation,
**options: Optional[Union[str, int, float, dict]],
) -> None:
"""
A method for changing the state of the chart.
Args:
*animations:
List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
**options: Dictionary of animation options for example `duration=1`.
For information on all available animation options see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).
Raises:
ValueError: If `animations` is not set.
Example:
Reset the chart styles:
chart.animate(Style(None))
""" # pylint: disable=line-too-long
if not animations:
raise ValueError("No animation was set.")
animation = AnimationMerger.merge_animations(animations)
animate = Animate(animation, options)
self._last_anim = uuid.uuid4().hex[:7]
self._display(
DisplayTemplate.ANIMATE.format(
display_target=self._display_target.value,
chart_id=self._chart_id,
anim_id=self._last_anim,
scroll=str(self._scroll_into_view).lower(),
**animate.dump(),
)
)
feature(name, enabled)
A method for turning on/off features of the chart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the chart feature. For information on all available features see the Vizzu Code reference. |
required |
enabled |
bool
|
The new state of the chart feature. |
required |
Example
Turn on tooltip
of the chart:
chart.feature("tooltip", True)
Source code in src/ipyvizzu/chart.py
def feature(self, name: str, enabled: bool) -> None:
"""
A method for turning on/off features of the chart.
Args:
name:
The name of the chart feature.
For information on all available features see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/modules/vizzu/#feature).
enabled: The new state of the chart feature.
Example:
Turn on `tooltip` of the chart:
chart.feature("tooltip", True)
""" # pylint: disable=line-too-long
self._display(
DisplayTemplate.FEATURE.format(
chart_id=self._chart_id,
**Feature(name, enabled).dump(),
)
)
plugin(plugin, options=None, name='default', enabled=True)
A method for register/unregister plugins of the chart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plugin |
str
|
The package name or the url of the plugin. |
required |
options |
Optional[dict]
|
The plugin constructor options. |
None
|
name |
str
|
The name of the plugin (default |
'default'
|
enabled |
bool
|
The state of the plugin (default |
True
|
Source code in src/ipyvizzu/chart.py
def plugin(
self,
plugin: str,
options: Optional[dict] = None,
name: str = "default",
enabled: bool = True,
) -> None:
"""
A method for register/unregister plugins of the chart.
Args:
plugin: The package name or the url of the plugin.
options: The plugin constructor options.
name: The name of the plugin (default `default`).
enabled: The state of the plugin (default `True`).
"""
self._display(
DisplayTemplate.PLUGIN.format(
chart_id=self._chart_id,
**Plugin(plugin, options, name, enabled).dump(),
)
)
store()
A method for saving and storing the actual state of the chart.
Returns:
Type | Description |
---|---|
Snapshot
|
A Snapshot object wich stores the actual state of the chart. |
Example
Save and restore the actual state of the chart:
snapshot = chart.store()
...
chart.animate(snapshot)
Source code in src/ipyvizzu/chart.py
def store(self) -> Snapshot:
"""
A method for saving and storing the actual state of the chart.
Returns:
A Snapshot object wich stores the actual state of the chart.
Example:
Save and restore the actual state of the chart:
snapshot = chart.store()
...
chart.animate(snapshot)
"""
snapshot_id = uuid.uuid4().hex[:7]
self._display(
DisplayTemplate.STORE.format(
chart_id=self._chart_id, **Store(snapshot_id).dump()
)
)
return Snapshot(snapshot_id)
on(event, handler)
A method for creating and turning on an event handler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The type of the event. For information on all available events see the Vizzu Code reference. |
required |
handler |
str
|
The JavaScript method of the event. |
required |
Returns:
Type | Description |
---|---|
EventHandler
|
The turned on event handler object. |
Example
Turn on an event handler which prints an alert message when someone clicks on the chart:
handler = chart.on("click", "alert(JSON.stringify(event.data));")
Source code in src/ipyvizzu/chart.py
def on( # pylint: disable=invalid-name
self, event: str, handler: str
) -> EventHandler:
"""
A method for creating and turning on an event handler.
Args:
event:
The type of the event.
For information on all available events see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/modules/events/).
handler: The JavaScript method of the event.
Returns:
The turned on event handler object.
Example:
Turn on an event handler which prints an alert message
when someone clicks on the chart:
handler = chart.on("click", "alert(JSON.stringify(event.data));")
""" # pylint: disable=line-too-long
event_handler = EventHandler(event, handler)
self._display(
DisplayTemplate.SET_EVENT.format(
chart_id=self._chart_id,
**EventOn(event_handler).dump(),
)
)
return event_handler
off(event_handler)
A method for turning off an event handler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_handler |
EventHandler
|
A previously created event handler object. |
required |
Example
Turn off a previously created event handler:
chart.off(handler)
Source code in src/ipyvizzu/chart.py
def off(self, event_handler: EventHandler) -> None:
"""
A method for turning off an event handler.
Args:
event_handler: A previously created event handler object.
Example:
Turn off a previously created event handler:
chart.off(handler)
"""
self._display(
DisplayTemplate.CLEAR_EVENT.format(
chart_id=self._chart_id,
**EventOff(event_handler).dump(),
)
)
log(chart_property)
A method for printing chart properties to the browser console.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chart_property |
ChartProperty
|
required |
Example
Log the actual style of the chart to the browser console:
chart.log(ChartProperty.STYLE)
Source code in src/ipyvizzu/chart.py
def log(self, chart_property: ChartProperty) -> None:
"""
A method for printing chart properties to the browser console.
Args:
chart_property:
A chart property such as
[CONFIG][ipyvizzu.template.ChartProperty] and
[STYLE][ipyvizzu.template.ChartProperty].
Example:
Log the actual style of the chart to the browser console:
chart.log(ChartProperty.STYLE)
"""
self._display(
DisplayTemplate.LOG.format(
chart_id=self._chart_id, **Log(chart_property).dump()
)
)
show()
A method for displaying the assembled JavaScript code.
Raises:
Type | Description |
---|---|
AssertionError
|
If display is not DisplayTarget.MANUAL. |
AssertionError
|
If chart already has been displayed. |
Source code in src/ipyvizzu/chart.py
def show(self) -> None:
"""
A method for displaying the assembled JavaScript code.
Raises:
AssertionError: If [display][ipyvizzu.Chart.__init__]
is not [DisplayTarget.MANUAL][ipyvizzu.template.DisplayTarget].
AssertionError: If chart already has been displayed.
"""
assert (
self._display_target == DisplayTarget.MANUAL
), "chart.show() can be used with display=DisplayTarget.MANUAL only"
assert not self._showed, "cannot be used after chart displayed"
display_javascript(
"\n".join(self._calls),
raw=True,
)
self._showed = True
ipyvizzu.Data
Bases: dict
, AbstractAnimation
A class for representing data animation. It can build data option of the chart.
Source code in src/ipyvizzu/animation.py
class Data(dict, AbstractAnimation):
"""
A class for representing data animation.
It can build data option of the chart.
"""
@classmethod
def filter(cls, filter_expr: Optional[str] = None) -> "Data":
"""
A class method for creating a [Data][ipyvizzu.animation.Data]
class instance with a data filter.
Args:
filter_expr: The JavaScript data filter expression.
Returns:
(Data): A data animation instance that contains a data filter.
Example:
Create a [Data][ipyvizzu.animation.Data] class with a data filter:
filter = Data.filter("record['Genres'] == 'Pop'")
"""
data = cls()
data.set_filter(filter_expr)
return data
def set_filter(self, filter_expr: Optional[str] = None) -> None:
"""
A method for adding a filter to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
filter_expr: The JavaScript data filter expression.
Example:
Add a data filter to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.set_filter("record['Genres'] == 'Pop'")
"""
filter_expr_raw_js = (
RawJavaScript(f"record => {{ return ({' '.join(filter_expr.split())}) }}")
if filter_expr is not None
else filter_expr
)
self.update({"filter": filter_expr_raw_js})
@classmethod
def from_json(cls, filename: Union[str, bytes, PathLike]) -> "Data":
"""
A method for returning a [Data][ipyvizzu.animation.Data]
class instance which has been created from a json file.
Args:
filename: The path of the data source json file.
Returns:
(Data): A data animation instance that has been created from a json file.
"""
with open(filename, "r", encoding="utf8") as file_desc:
return cls(json.load(file_desc))
def add_record(self, record: Record) -> None:
"""
A method for adding a record to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
record: A list that contains data values.
Example:
Adding a record to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
record = ["Pop", "Hard", 114]
data.add_record(record)
"""
self._add_value("records", record)
def add_records(self, records: List[Record]) -> None:
"""
A method for adding records to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
records: A list that contains data records.
Example:
Adding records to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
records = [
["Pop", "Hard", 114],
["Rock", "Hard", 96],
["Pop", "Experimental", 127],
["Rock", "Experimental", 83],
]
data.add_records(records)
"""
list(map(self.add_record, records))
def add_series(
self, name: str, values: Optional[SeriesValues] = None, **kwargs
) -> None:
"""
A method for adding a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the series.
values: The data values of the series.
**kwargs (Optional):
Arbitrary keyword arguments.
For example infer type can be set with the `type` keywod argument.
Example:
Adding a series without values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series("Genres")
Adding a series without values and with infer type to
a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series("Kinds", type="dimension")
Adding a series with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series(
"Popularity", [114, 96, 127, 83]
)
"""
self._add_named_value("series", name, values, **kwargs)
def add_series_list(self, series: List[Series]) -> None:
"""
A method for adding list of series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
series: List of series.
"""
if series:
self.setdefault("series", []).extend(series)
def add_dimension(
self, name: str, values: Optional[List[DimensionValue]] = None, **kwargs
) -> None:
"""
A method for adding a dimension to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the dimension.
values: The data values of the dimension.
**kwargs (Optional): Arbitrary keyword arguments.
Example:
Adding a dimension with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_dimension("Genres", ["Pop", "Rock"])
"""
self._add_named_value("dimensions", name, values, **kwargs)
def add_measure(
self, name: str, values: Optional[NestedMeasureValues] = None, **kwargs
) -> None:
"""
A method for adding a measure to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the measure.
values: The data values of the measure.
**kwargs (Optional): Arbitrary keyword arguments.
Example:
Adding a measure with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_measure(
"Popularity",
[
[114, 96],
[127, 83],
],
)
"""
self._add_named_value("measures", name, values, **kwargs)
def add_df(
self,
df: Optional[ # type: ignore
Union[
"pandas.DataFrame",
"pandas.Series",
"pyspark.sql.DataFrame",
]
],
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
max_rows: int = MAX_ROWS,
include_index: Optional[str] = None,
units: Optional[Dict[str, str]] = None,
) -> None:
"""
Add a `pandas` `DataFrame`, `Series` or a `pyspark` `DataFrame`
to an existing [Data][ipyvizzu.animation.Data] class instance.
Args:
df:
The `pandas` `DataFrame`, `Series` or the `pyspark` `DataFrame`to add.
default_measure_value:
The default measure value to fill empty values. Defaults to 0.
default_dimension_value:
The default dimension value to fill empty values. Defaults to an empty string.
max_rows:
The maximum number of rows to include in the converted series list.
If the `df` contains more rows,
a random sample of the given number of rows (approximately) will be taken.
include_index:
Add the data frame's index as a column with the given name. Defaults to `None`.
(Cannot be used with `pyspark` `DataFrame`.)
units:
A dictionary of column names and units. Defaults to `None`.
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
df = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_df(df)
"""
# pylint: disable=too-many-arguments
if not isinstance(df, type(None)):
arguments = {
"df": df,
"default_measure_value": default_measure_value,
"default_dimension_value": default_dimension_value,
"max_rows": max_rows,
"include_index": include_index,
"units": units,
}
Converter: Union[
Type[PandasDataFrameConverter], Type[SparkDataFrameConverter]
] = PandasDataFrameConverter
if isinstance(df, SparkDataFrame):
Converter = SparkDataFrameConverter
if arguments["include_index"] is not None:
raise ValueError(
"`include_index` cannot be used with `pyspark` `DataFrame`"
)
del arguments["include_index"]
converter = Converter(**arguments) # type: ignore
series_list = converter.get_series_list()
self.add_series_list(series_list)
def add_data_frame(
self,
data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
"""
[Deprecated] This function is deprecated and will be removed in future versions.
Use [add_df][ipyvizzu.animation.Data.add_df] function instead.
Add a `pandas` `DataFrame` or `Series` to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame:
The `pandas` `DataFrame` or `Series` to add.
default_measure_value:
The default measure value to fill empty values. Defaults to 0.
default_dimension_value:
The default dimension value to fill empty values. Defaults to an empty string.
"""
# pylint: disable=line-too-long
reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df"
warnings.warn(
f"'add_data_frame' is deprecated and will be removed in future versions. Use 'add_df' instead - see {reference}",
DeprecationWarning,
stacklevel=2,
)
self.add_df(
data_frame,
default_measure_value,
default_dimension_value,
max_rows=sys.maxsize,
)
def add_df_index(
self,
df: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
column_name: str = "Index",
max_rows: int = MAX_ROWS,
) -> None:
"""
Add the index of a `pandas` `DataFrame` as a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
df:
The `pandas` `DataFrame` or `Series` from which to extract the index.
column_name:
Name for the index column to add as a series.
max_rows:
The maximum number of rows to include in the converted series list.
If the `df` contains more rows,
a random sample of the given number of rows (approximately) will be taken.
Example:
Adding a data frame's index to a
[Data][ipyvizzu.animation.Data] class instance:
df = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_df_index(df, "DataFrameIndex")
data.add_df(df)
"""
if not isinstance(df, type(None)):
converter = PandasDataFrameConverter(
df, max_rows=max_rows, include_index=column_name
)
series_list = converter.get_series_from_index()
self.add_series_list(series_list)
def add_data_frame_index(
self,
data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
name: str,
) -> None:
"""
[Deprecated] This function is deprecated and will be removed in future versions.
Use [add_df_index][ipyvizzu.animation.Data.add_df_index] function instead.
Add the index of a `pandas` `DataFrame` as a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame:
The `pandas` `DataFrame` or `Series` from which to extract the index.
name:
The name of the index series.
"""
# pylint: disable=line-too-long
reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df_index"
warnings.warn(
f"'add_data_frame_index' is deprecated and will be removed in future versions. Use 'add_df_index' instead - see {reference}",
DeprecationWarning,
stacklevel=2,
)
self.add_df_index(data_frame, column_name=name, max_rows=sys.maxsize)
def add_np_array(
self,
np_array: Optional["numpy.array"], # type: ignore
column_name: Optional[ColumnName] = None,
column_dtype: Optional[ColumnDtype] = None,
column_unit: Optional[ColumnUnit] = None,
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
"""
Add a `numpy` `array` to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
np_array: The `numpy` `array` to add.
column_name:
The name of a column. By default, uses column indices. Can be set with an
Index:Name pair or, for single-dimensional arrays, with just the Name.
column_dtype:
The dtype of a column. By default, uses the np_array's dtype. Can be set
with an Index:DType pair or, for single-dimensional arrays, with just the DType.
default_measure_value:
Default value to use for missing measure values. Defaults to 0.
default_dimension_value:
Default value to use for missing dimension values. Defaults to an empty string.
column_unit:
The unit of a column. Defaults to `None`.
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
np_array = np.zeros((3, 4))
data = Data()
data.add_np_array(np_array)
"""
# pylint: disable=too-many-arguments
if not isinstance(np_array, type(None)):
converter = NumpyArrayConverter(
np_array,
column_name,
column_dtype,
column_unit,
default_measure_value,
default_dimension_value,
)
series_list = converter.get_series_list()
self.add_series_list(series_list)
def _add_named_value(
self,
dest: str,
name: str,
values: Optional[
Union[
SeriesValues,
NestedMeasureValues,
]
] = None,
**kwargs,
) -> None:
value = {"name": name, **kwargs}
if values is not None:
value["values"] = values
self._add_value(dest, value)
def _add_value(self, dest: str, value: Union[dict, list]) -> None:
self.setdefault(dest, []).append(value)
def build(self) -> dict:
"""
A method for validating and returning the data animation dictionary.
Returns:
A dictionary that stored in the data animation object.
It contains a `data` key whose value is the stored animation.
"""
jsonschema.validate(self, DATA_SCHEMA)
return {"data": self}
filter(filter_expr=None)
classmethod
A class method for creating a Data class instance with a data filter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_expr |
Optional[str]
|
The JavaScript data filter expression. |
None
|
Returns:
Type | Description |
---|---|
Data
|
A data animation instance that contains a data filter. |
Source code in src/ipyvizzu/animation.py
@classmethod
def filter(cls, filter_expr: Optional[str] = None) -> "Data":
"""
A class method for creating a [Data][ipyvizzu.animation.Data]
class instance with a data filter.
Args:
filter_expr: The JavaScript data filter expression.
Returns:
(Data): A data animation instance that contains a data filter.
Example:
Create a [Data][ipyvizzu.animation.Data] class with a data filter:
filter = Data.filter("record['Genres'] == 'Pop'")
"""
data = cls()
data.set_filter(filter_expr)
return data
set_filter(filter_expr=None)
A method for adding a filter to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_expr |
Optional[str]
|
The JavaScript data filter expression. |
None
|
Example
Add a data filter to a Data class instance:
data = Data()
data.set_filter("record['Genres'] == 'Pop'")
Source code in src/ipyvizzu/animation.py
def set_filter(self, filter_expr: Optional[str] = None) -> None:
"""
A method for adding a filter to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
filter_expr: The JavaScript data filter expression.
Example:
Add a data filter to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.set_filter("record['Genres'] == 'Pop'")
"""
filter_expr_raw_js = (
RawJavaScript(f"record => {{ return ({' '.join(filter_expr.split())}) }}")
if filter_expr is not None
else filter_expr
)
self.update({"filter": filter_expr_raw_js})
from_json(filename)
classmethod
A method for returning a Data class instance which has been created from a json file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename |
Union[str, bytes, PathLike]
|
The path of the data source json file. |
required |
Returns:
Type | Description |
---|---|
Data
|
A data animation instance that has been created from a json file. |
Source code in src/ipyvizzu/animation.py
@classmethod
def from_json(cls, filename: Union[str, bytes, PathLike]) -> "Data":
"""
A method for returning a [Data][ipyvizzu.animation.Data]
class instance which has been created from a json file.
Args:
filename: The path of the data source json file.
Returns:
(Data): A data animation instance that has been created from a json file.
"""
with open(filename, "r", encoding="utf8") as file_desc:
return cls(json.load(file_desc))
add_record(record)
A method for adding a record to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
record |
Record
|
A list that contains data values. |
required |
Example
Adding a record to a Data class instance:
data = Data()
record = ["Pop", "Hard", 114]
data.add_record(record)
Source code in src/ipyvizzu/animation.py
def add_record(self, record: Record) -> None:
"""
A method for adding a record to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
record: A list that contains data values.
Example:
Adding a record to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
record = ["Pop", "Hard", 114]
data.add_record(record)
"""
self._add_value("records", record)
add_records(records)
A method for adding records to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
records |
List[Record]
|
A list that contains data records. |
required |
Example
Adding records to a Data class instance:
data = Data()
records = [
["Pop", "Hard", 114],
["Rock", "Hard", 96],
["Pop", "Experimental", 127],
["Rock", "Experimental", 83],
]
data.add_records(records)
Source code in src/ipyvizzu/animation.py
def add_records(self, records: List[Record]) -> None:
"""
A method for adding records to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
records: A list that contains data records.
Example:
Adding records to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
records = [
["Pop", "Hard", 114],
["Rock", "Hard", 96],
["Pop", "Experimental", 127],
["Rock", "Experimental", 83],
]
data.add_records(records)
"""
list(map(self.add_record, records))
add_series(name, values=None, **kwargs)
A method for adding a series to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the series. |
required |
values |
Optional[SeriesValues]
|
The data values of the series. |
None
|
**kwargs |
Optional
|
Arbitrary keyword arguments. For example infer type can be set with the |
{}
|
Example
Adding a series without values to a Data class instance:
data = Data()
data.add_series("Genres")
Adding a series without values and with infer type to a Data class instance:
data = Data()
data.add_series("Kinds", type="dimension")
Adding a series with values to a Data class instance:
data = Data()
data.add_series(
"Popularity", [114, 96, 127, 83]
)
Source code in src/ipyvizzu/animation.py
def add_series(
self, name: str, values: Optional[SeriesValues] = None, **kwargs
) -> None:
"""
A method for adding a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the series.
values: The data values of the series.
**kwargs (Optional):
Arbitrary keyword arguments.
For example infer type can be set with the `type` keywod argument.
Example:
Adding a series without values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series("Genres")
Adding a series without values and with infer type to
a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series("Kinds", type="dimension")
Adding a series with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_series(
"Popularity", [114, 96, 127, 83]
)
"""
self._add_named_value("series", name, values, **kwargs)
add_series_list(series)
A method for adding list of series to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
series |
List[Series]
|
List of series. |
required |
Source code in src/ipyvizzu/animation.py
def add_series_list(self, series: List[Series]) -> None:
"""
A method for adding list of series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
series: List of series.
"""
if series:
self.setdefault("series", []).extend(series)
add_dimension(name, values=None, **kwargs)
A method for adding a dimension to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the dimension. |
required |
values |
Optional[List[DimensionValue]]
|
The data values of the dimension. |
None
|
**kwargs |
Optional
|
Arbitrary keyword arguments. |
{}
|
Example
Adding a dimension with values to a Data class instance:
data = Data()
data.add_dimension("Genres", ["Pop", "Rock"])
Source code in src/ipyvizzu/animation.py
def add_dimension(
self, name: str, values: Optional[List[DimensionValue]] = None, **kwargs
) -> None:
"""
A method for adding a dimension to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the dimension.
values: The data values of the dimension.
**kwargs (Optional): Arbitrary keyword arguments.
Example:
Adding a dimension with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_dimension("Genres", ["Pop", "Rock"])
"""
self._add_named_value("dimensions", name, values, **kwargs)
add_measure(name, values=None, **kwargs)
A method for adding a measure to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the measure. |
required |
values |
Optional[NestedMeasureValues]
|
The data values of the measure. |
None
|
**kwargs |
Optional
|
Arbitrary keyword arguments. |
{}
|
Example
Adding a measure with values to a Data class instance:
data = Data()
data.add_measure(
"Popularity",
[
[114, 96],
[127, 83],
],
)
Source code in src/ipyvizzu/animation.py
def add_measure(
self, name: str, values: Optional[NestedMeasureValues] = None, **kwargs
) -> None:
"""
A method for adding a measure to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
name: The name of the measure.
values: The data values of the measure.
**kwargs (Optional): Arbitrary keyword arguments.
Example:
Adding a measure with values to a [Data][ipyvizzu.animation.Data] class instance:
data = Data()
data.add_measure(
"Popularity",
[
[114, 96],
[127, 83],
],
)
"""
self._add_named_value("measures", name, values, **kwargs)
add_df(df, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION, max_rows=MAX_ROWS, include_index=None, units=None)
Add a pandas
DataFrame
, Series
or a pyspark
DataFrame
to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
Optional[Union[DataFrame, Series, DataFrame]]
|
The |
required |
default_measure_value |
MeasureValue
|
The default measure value to fill empty values. Defaults to 0. |
NAN_MEASURE
|
default_dimension_value |
DimensionValue
|
The default dimension value to fill empty values. Defaults to an empty string. |
NAN_DIMENSION
|
max_rows |
int
|
The maximum number of rows to include in the converted series list.
If the |
MAX_ROWS
|
include_index |
Optional[str]
|
Add the data frame's index as a column with the given name. Defaults to |
None
|
units |
Optional[Dict[str, str]]
|
A dictionary of column names and units. Defaults to |
None
|
Example
Adding a data frame to a Data class instance:
df = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_df(df)
Source code in src/ipyvizzu/animation.py
def add_df(
self,
df: Optional[ # type: ignore
Union[
"pandas.DataFrame",
"pandas.Series",
"pyspark.sql.DataFrame",
]
],
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
max_rows: int = MAX_ROWS,
include_index: Optional[str] = None,
units: Optional[Dict[str, str]] = None,
) -> None:
"""
Add a `pandas` `DataFrame`, `Series` or a `pyspark` `DataFrame`
to an existing [Data][ipyvizzu.animation.Data] class instance.
Args:
df:
The `pandas` `DataFrame`, `Series` or the `pyspark` `DataFrame`to add.
default_measure_value:
The default measure value to fill empty values. Defaults to 0.
default_dimension_value:
The default dimension value to fill empty values. Defaults to an empty string.
max_rows:
The maximum number of rows to include in the converted series list.
If the `df` contains more rows,
a random sample of the given number of rows (approximately) will be taken.
include_index:
Add the data frame's index as a column with the given name. Defaults to `None`.
(Cannot be used with `pyspark` `DataFrame`.)
units:
A dictionary of column names and units. Defaults to `None`.
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
df = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_df(df)
"""
# pylint: disable=too-many-arguments
if not isinstance(df, type(None)):
arguments = {
"df": df,
"default_measure_value": default_measure_value,
"default_dimension_value": default_dimension_value,
"max_rows": max_rows,
"include_index": include_index,
"units": units,
}
Converter: Union[
Type[PandasDataFrameConverter], Type[SparkDataFrameConverter]
] = PandasDataFrameConverter
if isinstance(df, SparkDataFrame):
Converter = SparkDataFrameConverter
if arguments["include_index"] is not None:
raise ValueError(
"`include_index` cannot be used with `pyspark` `DataFrame`"
)
del arguments["include_index"]
converter = Converter(**arguments) # type: ignore
series_list = converter.get_series_list()
self.add_series_list(series_list)
add_data_frame(data_frame, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION)
[Deprecated] This function is deprecated and will be removed in future versions. Use add_df function instead.
Add a pandas
DataFrame
or Series
to an existing
Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_frame |
Optional[Union[DataFrame, Series]]
|
The |
required |
default_measure_value |
MeasureValue
|
The default measure value to fill empty values. Defaults to 0. |
NAN_MEASURE
|
default_dimension_value |
DimensionValue
|
The default dimension value to fill empty values. Defaults to an empty string. |
NAN_DIMENSION
|
Source code in src/ipyvizzu/animation.py
def add_data_frame(
self,
data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
"""
[Deprecated] This function is deprecated and will be removed in future versions.
Use [add_df][ipyvizzu.animation.Data.add_df] function instead.
Add a `pandas` `DataFrame` or `Series` to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame:
The `pandas` `DataFrame` or `Series` to add.
default_measure_value:
The default measure value to fill empty values. Defaults to 0.
default_dimension_value:
The default dimension value to fill empty values. Defaults to an empty string.
"""
# pylint: disable=line-too-long
reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df"
warnings.warn(
f"'add_data_frame' is deprecated and will be removed in future versions. Use 'add_df' instead - see {reference}",
DeprecationWarning,
stacklevel=2,
)
self.add_df(
data_frame,
default_measure_value,
default_dimension_value,
max_rows=sys.maxsize,
)
add_df_index(df, column_name='Index', max_rows=MAX_ROWS)
Add the index of a pandas
DataFrame
as a series to an existing
Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
Optional[Union[DataFrame, Series]]
|
The |
required |
column_name |
str
|
Name for the index column to add as a series. |
'Index'
|
max_rows |
int
|
The maximum number of rows to include in the converted series list.
If the |
MAX_ROWS
|
Example
Adding a data frame's index to a Data class instance:
df = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_df_index(df, "DataFrameIndex")
data.add_df(df)
Source code in src/ipyvizzu/animation.py
def add_df_index(
self,
df: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
column_name: str = "Index",
max_rows: int = MAX_ROWS,
) -> None:
"""
Add the index of a `pandas` `DataFrame` as a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
df:
The `pandas` `DataFrame` or `Series` from which to extract the index.
column_name:
Name for the index column to add as a series.
max_rows:
The maximum number of rows to include in the converted series list.
If the `df` contains more rows,
a random sample of the given number of rows (approximately) will be taken.
Example:
Adding a data frame's index to a
[Data][ipyvizzu.animation.Data] class instance:
df = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_df_index(df, "DataFrameIndex")
data.add_df(df)
"""
if not isinstance(df, type(None)):
converter = PandasDataFrameConverter(
df, max_rows=max_rows, include_index=column_name
)
series_list = converter.get_series_from_index()
self.add_series_list(series_list)
add_data_frame_index(data_frame, name)
[Deprecated] This function is deprecated and will be removed in future versions. Use add_df_index function instead.
Add the index of a pandas
DataFrame
as a series to an existing
Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_frame |
Optional[Union[DataFrame, Series]]
|
The |
required |
name |
str
|
The name of the index series. |
required |
Source code in src/ipyvizzu/animation.py
def add_data_frame_index(
self,
data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]], # type: ignore
name: str,
) -> None:
"""
[Deprecated] This function is deprecated and will be removed in future versions.
Use [add_df_index][ipyvizzu.animation.Data.add_df_index] function instead.
Add the index of a `pandas` `DataFrame` as a series to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame:
The `pandas` `DataFrame` or `Series` from which to extract the index.
name:
The name of the index series.
"""
# pylint: disable=line-too-long
reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df_index"
warnings.warn(
f"'add_data_frame_index' is deprecated and will be removed in future versions. Use 'add_df_index' instead - see {reference}",
DeprecationWarning,
stacklevel=2,
)
self.add_df_index(data_frame, column_name=name, max_rows=sys.maxsize)
add_np_array(np_array, column_name=None, column_dtype=None, column_unit=None, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION)
Add a numpy
array
to an existing
Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
np_array |
Optional[array]
|
The |
required |
column_name |
Optional[ColumnName]
|
The name of a column. By default, uses column indices. Can be set with an Index:Name pair or, for single-dimensional arrays, with just the Name. |
None
|
column_dtype |
Optional[ColumnDtype]
|
The dtype of a column. By default, uses the np_array's dtype. Can be set with an Index:DType pair or, for single-dimensional arrays, with just the DType. |
None
|
default_measure_value |
MeasureValue
|
Default value to use for missing measure values. Defaults to 0. |
NAN_MEASURE
|
default_dimension_value |
DimensionValue
|
Default value to use for missing dimension values. Defaults to an empty string. |
NAN_DIMENSION
|
column_unit |
Optional[ColumnUnit]
|
The unit of a column. Defaults to |
None
|
Example
Adding a data frame to a Data class instance:
np_array = np.zeros((3, 4))
data = Data()
data.add_np_array(np_array)
Source code in src/ipyvizzu/animation.py
def add_np_array(
self,
np_array: Optional["numpy.array"], # type: ignore
column_name: Optional[ColumnName] = None,
column_dtype: Optional[ColumnDtype] = None,
column_unit: Optional[ColumnUnit] = None,
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
"""
Add a `numpy` `array` to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
np_array: The `numpy` `array` to add.
column_name:
The name of a column. By default, uses column indices. Can be set with an
Index:Name pair or, for single-dimensional arrays, with just the Name.
column_dtype:
The dtype of a column. By default, uses the np_array's dtype. Can be set
with an Index:DType pair or, for single-dimensional arrays, with just the DType.
default_measure_value:
Default value to use for missing measure values. Defaults to 0.
default_dimension_value:
Default value to use for missing dimension values. Defaults to an empty string.
column_unit:
The unit of a column. Defaults to `None`.
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
np_array = np.zeros((3, 4))
data = Data()
data.add_np_array(np_array)
"""
# pylint: disable=too-many-arguments
if not isinstance(np_array, type(None)):
converter = NumpyArrayConverter(
np_array,
column_name,
column_dtype,
column_unit,
default_measure_value,
default_dimension_value,
)
series_list = converter.get_series_list()
self.add_series_list(series_list)
build()
A method for validating and returning the data animation dictionary.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the data animation object.
It contains a |
Source code in src/ipyvizzu/animation.py
def build(self) -> dict:
"""
A method for validating and returning the data animation dictionary.
Returns:
A dictionary that stored in the data animation object.
It contains a `data` key whose value is the stored animation.
"""
jsonschema.validate(self, DATA_SCHEMA)
return {"data": self}
ipyvizzu.Config
Bases: AbstractAnimation
A class for representing config animation. It can build config option of the chart.
Source code in src/ipyvizzu/animation.py
class Config(AbstractAnimation, metaclass=ConfigAttr):
"""
A class for representing config animation.
It can build config option of the chart.
"""
def __init__(self, data: Optional[Union[dict, RawJavaScript]]):
"""
Config constructor.
Args:
data:
A config animation dictionary.
For information on all available config parameters see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_config.Chart/).
""" # pylint: disable=line-too-long
self._data = data
def build(self) -> dict:
"""
A method for returning the config animation dictionary.
Returns:
A dictionary that stored in the config animation object.
It contains a `config` key whose value is the stored animation.
"""
return {"config": self._data}
__init__(data)
Config constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
Optional[Union[dict, RawJavaScript]]
|
A config animation dictionary. For information on all available config parameters see the Vizzu Code reference. |
required |
Source code in src/ipyvizzu/animation.py
def __init__(self, data: Optional[Union[dict, RawJavaScript]]):
"""
Config constructor.
Args:
data:
A config animation dictionary.
For information on all available config parameters see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_config.Chart/).
""" # pylint: disable=line-too-long
self._data = data
build()
A method for returning the config animation dictionary.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the config animation object.
It contains a |
Source code in src/ipyvizzu/animation.py
def build(self) -> dict:
"""
A method for returning the config animation dictionary.
Returns:
A dictionary that stored in the config animation object.
It contains a `config` key whose value is the stored animation.
"""
return {"config": self._data}
ipyvizzu.Style
Bases: AbstractAnimation
A class for representing style animation. It can build style option of the chart.
Source code in src/ipyvizzu/animation.py
class Style(AbstractAnimation):
"""
A class for representing style animation.
It can build style option of the chart.
"""
def __init__(self, data: Optional[dict]):
"""
Style constructor.
Args:
data:
A style animation dictionary.
For information on all available style parameters see the [Style][styling-properties]
chapter or the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_styles.Chart/).
""" # pylint: disable=line-too-long
self._data = data
def build(self) -> dict:
"""
A method for returning the style animation dictionary.
Returns:
A dictionary that stored in the style animation object.
It contains a `style` key whose value is the stored animation.
"""
return {"style": self._data}
__init__(data)
Style constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
Optional[dict]
|
A style animation dictionary. For information on all available style parameters see the Style chapter or the Vizzu Code reference. |
required |
Source code in src/ipyvizzu/animation.py
def __init__(self, data: Optional[dict]):
"""
Style constructor.
Args:
data:
A style animation dictionary.
For information on all available style parameters see the [Style][styling-properties]
chapter or the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_styles.Chart/).
""" # pylint: disable=line-too-long
self._data = data
build()
A method for returning the style animation dictionary.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the style animation object.
It contains a |
Source code in src/ipyvizzu/animation.py
def build(self) -> dict:
"""
A method for returning the style animation dictionary.
Returns:
A dictionary that stored in the style animation object.
It contains a `style` key whose value is the stored animation.
"""
return {"style": self._data}
ipyvizzu.Keyframe
Bases: AbstractAnimation
A class for representing keyframe animation. It can build keyframe of the chart.
Source code in src/ipyvizzu/animation.py
class Keyframe(AbstractAnimation):
"""
A class for representing keyframe animation.
It can build keyframe of the chart.
"""
def __init__(
self,
*animations: AbstractAnimation,
**options: Optional[Union[str, int, float, dict]],
):
"""
Keyframe constructor.
Args:
*animations:
List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
**options: Dictionary of animation options for example `duration=1`.
For information on all available animation options see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).
Raises:
ValueError: If `animations` is not set.
ValueError: If initialized with a `Keyframe`.
""" # pylint: disable=line-too-long
if not animations:
raise ValueError("No animation was set.")
if [animation for animation in animations if isinstance(animation, Keyframe)]:
raise ValueError("A Keyframe cannot contain a Keyframe.")
self._keyframe = {}
self._keyframe["target"] = AnimationMerger.merge_animations(animations).build()
if options:
self._keyframe["options"] = options
def build(self) -> dict:
"""
A method for returning the keyframe animation dictionary.
Returns:
A dictionary that stored in the keyframe animation object.
It contains a `target` key whose value is the stored animation
and an optional `options` key whose value is the stored animation options.
"""
return self._keyframe
__init__(*animations, **options)
Keyframe constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*animations |
AbstractAnimation
|
()
|
|
**options |
Optional[Union[str, int, float, dict]]
|
Dictionary of animation options for example |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If initialized with a |
Source code in src/ipyvizzu/animation.py
def __init__(
self,
*animations: AbstractAnimation,
**options: Optional[Union[str, int, float, dict]],
):
"""
Keyframe constructor.
Args:
*animations:
List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
**options: Dictionary of animation options for example `duration=1`.
For information on all available animation options see the
[Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).
Raises:
ValueError: If `animations` is not set.
ValueError: If initialized with a `Keyframe`.
""" # pylint: disable=line-too-long
if not animations:
raise ValueError("No animation was set.")
if [animation for animation in animations if isinstance(animation, Keyframe)]:
raise ValueError("A Keyframe cannot contain a Keyframe.")
self._keyframe = {}
self._keyframe["target"] = AnimationMerger.merge_animations(animations).build()
if options:
self._keyframe["options"] = options
build()
A method for returning the keyframe animation dictionary.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the keyframe animation object.
It contains a |
Source code in src/ipyvizzu/animation.py
def build(self) -> dict:
"""
A method for returning the keyframe animation dictionary.
Returns:
A dictionary that stored in the keyframe animation object.
It contains a `target` key whose value is the stored animation
and an optional `options` key whose value is the stored animation options.
"""
return self._keyframe
ipyvizzu.Snapshot
Bases: AbstractAnimation
A class for representing a stored chart state. It can build the snapshot id of the chart.
Source code in src/ipyvizzu/animation.py
class Snapshot(AbstractAnimation):
"""
A class for representing a stored chart state.
It can build the snapshot id of the chart.
"""
def __init__(self, snapshot_id: str):
"""
Snapshot constructor.
Args:
snapshot_id: A snapshot id.
"""
self._snapshot_id = snapshot_id
def build(self) -> str: # type: ignore
"""
A method for returning the snapshot id str.
Returns:
An str snapshot id that stored in the snapshot animation object.
"""
return self._snapshot_id
__init__(snapshot_id)
Snapshot constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
snapshot_id |
str
|
A snapshot id. |
required |
Source code in src/ipyvizzu/animation.py
def __init__(self, snapshot_id: str):
"""
Snapshot constructor.
Args:
snapshot_id: A snapshot id.
"""
self._snapshot_id = snapshot_id
build()
A method for returning the snapshot id str.
Returns:
Type | Description |
---|---|
str
|
An str snapshot id that stored in the snapshot animation object. |
Source code in src/ipyvizzu/animation.py
def build(self) -> str: # type: ignore
"""
A method for returning the snapshot id str.
Returns:
An str snapshot id that stored in the snapshot animation object.
"""
return self._snapshot_id
ipyvizzu.Animation
Bases: Snapshot
A class for representing a stored animation. It can build the snapshot id of the animation.
Source code in src/ipyvizzu/animation.py
class Animation(Snapshot):
"""
A class for representing a stored animation.
It can build the snapshot id of the animation.
"""
ipyvizzu.AbstractAnimation
An abstract class for representing animation objects
that have dump
and build
methods.
Source code in src/ipyvizzu/animation.py
class AbstractAnimation:
"""
An abstract class for representing animation objects
that have `dump` and `build` methods.
"""
def dump(self) -> str:
"""
A method for converting the built dictionary into string.
Returns:
An str that has been json dumped with
[RawJavaScriptEncoder][ipyvizzu.json.RawJavaScriptEncoder] from a dictionary.
"""
return json.dumps(self.build(), cls=RawJavaScriptEncoder)
@abc.abstractmethod
def build(self) -> dict:
"""
An abstract method for returning a dictionary with values
that can be converted into json string.
Returns:
A dictionary that stored in the animation object.
"""
dump()
A method for converting the built dictionary into string.
Returns:
Type | Description |
---|---|
str
|
An str that has been json dumped with RawJavaScriptEncoder from a dictionary. |
Source code in src/ipyvizzu/animation.py
def dump(self) -> str:
"""
A method for converting the built dictionary into string.
Returns:
An str that has been json dumped with
[RawJavaScriptEncoder][ipyvizzu.json.RawJavaScriptEncoder] from a dictionary.
"""
return json.dumps(self.build(), cls=RawJavaScriptEncoder)
build()
abstractmethod
An abstract method for returning a dictionary with values that can be converted into json string.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the animation object. |
Source code in src/ipyvizzu/animation.py
@abc.abstractmethod
def build(self) -> dict:
"""
An abstract method for returning a dictionary with values
that can be converted into json string.
Returns:
A dictionary that stored in the animation object.
"""
ipyvizzu.PlainAnimation
Bases: dict
, AbstractAnimation
A class for representing plain animation. It can build any dictionary.
Source code in src/ipyvizzu/animation.py
class PlainAnimation(dict, AbstractAnimation):
"""
A class for representing plain animation.
It can build any dictionary.
"""
def build(self) -> dict:
"""
A method for returning the plain animation dictionary.
Returns:
A dictionary that stored in the plain animation object.
"""
return self
build()
A method for returning the plain animation dictionary.
Returns:
Type | Description |
---|---|
dict
|
A dictionary that stored in the plain animation object. |
Source code in src/ipyvizzu/animation.py
def build(self) -> dict:
"""
A method for returning the plain animation dictionary.
Returns:
A dictionary that stored in the plain animation object.
"""
return self
ipyvizzu.AnimationMerger
Bases: AbstractAnimation
A class for merging different types of animations.
Source code in src/ipyvizzu/animation.py
class AnimationMerger(AbstractAnimation):
"""A class for merging different types of animations."""
def __init__(self) -> None:
"""AnimationMerger constructor."""
self._dict: dict = {}
self._list: list = []
@classmethod
def merge_animations(
cls, animations: Tuple[AbstractAnimation, ...]
) -> AbstractAnimation:
"""
A class method for merging animations.
Args:
animations: List of `AbstractAnimation` inherited objects.
Returns:
An `AnimationMerger` class with the merged animations.
"""
if len(animations) == 1 and not isinstance(animations[0], Keyframe):
return animations[0]
merger = cls()
for animation in animations:
merger.merge(animation)
return merger
def merge(self, animation: AbstractAnimation) -> None:
"""
A method for merging an animation with the previously merged animations.
Args:
animation: An animation to be merged with with previously merged animations.
Raises:
ValueError: If the type of an animation is already merged.
ValueError: If `Keyframe` is merged with different type of animation.
"""
if isinstance(animation, Keyframe):
if self._dict:
raise ValueError("Keyframe cannot be merged with other animations.")
data = animation.build()
self._list.append(data)
else:
if self._list:
raise ValueError("Keyframe cannot be merged with other animations.")
data = self._validate(animation)
self._dict.update(data)
def _validate(self, animation: AbstractAnimation) -> dict:
if isinstance(animation, Snapshot):
raise ValueError("Snapshot cannot be merged with other animations.")
data = animation.build()
common_keys = set(data).intersection(self._dict)
if common_keys:
raise ValueError(f"{common_keys} is already merged.")
return data
def build(self) -> Union[dict, list]: # type: ignore
"""
A method for returning a merged list of `Keyframes`
or a merged dictionary from different types of animations.
Returns:
A merged list of [Keyframes][ipyvizzu.animation.Keyframe] or
a merged dictionary from
[Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and
[Style][ipyvizzu.animation.Style] animations.
"""
if self._dict:
return self._dict
return self._list
__init__()
AnimationMerger constructor.
Source code in src/ipyvizzu/animation.py
def __init__(self) -> None:
"""AnimationMerger constructor."""
self._dict: dict = {}
self._list: list = []
merge_animations(animations)
classmethod
A class method for merging animations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
animations |
Tuple[AbstractAnimation, ...]
|
List of |
required |
Returns:
Type | Description |
---|---|
AbstractAnimation
|
An |
Source code in src/ipyvizzu/animation.py
@classmethod
def merge_animations(
cls, animations: Tuple[AbstractAnimation, ...]
) -> AbstractAnimation:
"""
A class method for merging animations.
Args:
animations: List of `AbstractAnimation` inherited objects.
Returns:
An `AnimationMerger` class with the merged animations.
"""
if len(animations) == 1 and not isinstance(animations[0], Keyframe):
return animations[0]
merger = cls()
for animation in animations:
merger.merge(animation)
return merger
merge(animation)
A method for merging an animation with the previously merged animations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
animation |
AbstractAnimation
|
An animation to be merged with with previously merged animations. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the type of an animation is already merged. |
ValueError
|
If |
Source code in src/ipyvizzu/animation.py
def merge(self, animation: AbstractAnimation) -> None:
"""
A method for merging an animation with the previously merged animations.
Args:
animation: An animation to be merged with with previously merged animations.
Raises:
ValueError: If the type of an animation is already merged.
ValueError: If `Keyframe` is merged with different type of animation.
"""
if isinstance(animation, Keyframe):
if self._dict:
raise ValueError("Keyframe cannot be merged with other animations.")
data = animation.build()
self._list.append(data)
else:
if self._list:
raise ValueError("Keyframe cannot be merged with other animations.")
data = self._validate(animation)
self._dict.update(data)
build()
A method for returning a merged list of Keyframes
or a merged dictionary from different types of animations.
Returns:
Type | Description |
---|---|
Union[dict, list]
|
Source code in src/ipyvizzu/animation.py
def build(self) -> Union[dict, list]: # type: ignore
"""
A method for returning a merged list of `Keyframes`
or a merged dictionary from different types of animations.
Returns:
A merged list of [Keyframes][ipyvizzu.animation.Keyframe] or
a merged dictionary from
[Data][ipyvizzu.animation.Data],
[Config][ipyvizzu.animation.Config] and
[Style][ipyvizzu.animation.Style] animations.
"""
if self._dict:
return self._dict
return self._list
ipyvizzu.Animate
Bases: Method
It stores and dumps chart_target
and chart_anim_opts
parameters.
Source code in src/ipyvizzu/method.py
class Animate(Method):
"""
It stores and dumps `chart_target` and `chart_anim_opts` parameters.
"""
# pylint: disable=too-few-public-methods
def __init__(
self,
chart_target: AbstractAnimation,
chart_anim_opts: Optional[dict] = None,
):
"""
Animate constructor.
Args:
chart_target:
AbstractAnimation inherited object such as
[Data][ipyvizzu.animation.Data]
[Config][ipyvizzu.animation.Config] or
[Style][ipyvizzu.animation.Style].
chart_anim_opts:
Animation options' dictionary. If it is not set, it dumps `undefined`.
"""
self._data = {
"chart_target": chart_target.dump(),
"chart_anim_opts": (
PlainAnimation(chart_anim_opts).dump()
if chart_anim_opts
else "undefined"
),
}
__init__(chart_target, chart_anim_opts=None)
Animate constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chart_target |
AbstractAnimation
|
required | |
chart_anim_opts |
Optional[dict]
|
Animation options' dictionary. If it is not set, it dumps |
None
|
Source code in src/ipyvizzu/method.py
def __init__(
self,
chart_target: AbstractAnimation,
chart_anim_opts: Optional[dict] = None,
):
"""
Animate constructor.
Args:
chart_target:
AbstractAnimation inherited object such as
[Data][ipyvizzu.animation.Data]
[Config][ipyvizzu.animation.Config] or
[Style][ipyvizzu.animation.Style].
chart_anim_opts:
Animation options' dictionary. If it is not set, it dumps `undefined`.
"""
self._data = {
"chart_target": chart_target.dump(),
"chart_anim_opts": (
PlainAnimation(chart_anim_opts).dump()
if chart_anim_opts
else "undefined"
),
}
ipyvizzu.Feature
Bases: Method
It stores and dumps name
and enabled
parameters.
Source code in src/ipyvizzu/method.py
class Feature(Method):
"""
It stores and dumps `name` and `enabled` parameters.
"""
# pylint: disable=too-few-public-methods
def __init__(self, name: str, enabled: bool):
"""
Feature constructor.
Args:
name: The name of a chart feature.
enabled: The new state of a chart feature.
"""
self._data = {"name": name, "enabled": json.dumps(enabled)}
__init__(name, enabled)
Feature constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of a chart feature. |
required |
enabled |
bool
|
The new state of a chart feature. |
required |
Source code in src/ipyvizzu/method.py
def __init__(self, name: str, enabled: bool):
"""
Feature constructor.
Args:
name: The name of a chart feature.
enabled: The new state of a chart feature.
"""
self._data = {"name": name, "enabled": json.dumps(enabled)}
ipyvizzu.Store
Bases: Method
It stores and dumps snapshot_id
parameter.
Source code in src/ipyvizzu/method.py
class Store(Method):
"""
It stores and dumps `snapshot_id` parameter.
"""
# pylint: disable=too-few-public-methods
def __init__(self, snapshot_id: str):
"""
Store constructor.
Args:
snapshot_id: The id of snapshot object.
"""
self._data = {"id": snapshot_id}
__init__(snapshot_id)
Store constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
snapshot_id |
str
|
The id of snapshot object. |
required |
Source code in src/ipyvizzu/method.py
def __init__(self, snapshot_id: str):
"""
Store constructor.
Args:
snapshot_id: The id of snapshot object.
"""
self._data = {"id": snapshot_id}
ipyvizzu.EventOn
Bases: Method
It stores and dumps the id
, the event
and the handler
of the event handler object.
Source code in src/ipyvizzu/method.py
class EventOn(Method):
"""
It stores and dumps the `id`, the `event` and the `handler` of the event handler object.
"""
# pylint: disable=too-few-public-methods
def __init__(self, event_handler: EventHandler):
"""
EventOn constructor.
Args:
event_handler: An event handler object.
"""
self._data = {
"id": event_handler.id,
"event": event_handler.event,
"handler": event_handler.handler,
}
__init__(event_handler)
EventOn constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_handler |
EventHandler
|
An event handler object. |
required |
Source code in src/ipyvizzu/method.py
def __init__(self, event_handler: EventHandler):
"""
EventOn constructor.
Args:
event_handler: An event handler object.
"""
self._data = {
"id": event_handler.id,
"event": event_handler.event,
"handler": event_handler.handler,
}
ipyvizzu.EventOff
Bases: Method
It stores and dumps the id
and the event
of the event handler object.
Source code in src/ipyvizzu/method.py
class EventOff(Method):
"""
It stores and dumps the `id` and the `event` of the event handler object.
"""
# pylint: disable=too-few-public-methods
def __init__(self, event_handler: EventHandler):
"""
EventOff constructor.
Args:
event_handler: An event handler object.
"""
self._data = {"id": event_handler.id, "event": event_handler.event}
__init__(event_handler)
EventOff constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_handler |
EventHandler
|
An event handler object. |
required |
Source code in src/ipyvizzu/method.py
def __init__(self, event_handler: EventHandler):
"""
EventOff constructor.
Args:
event_handler: An event handler object.
"""
self._data = {"id": event_handler.id, "event": event_handler.event}
ipyvizzu.Log
Bases: Method
It stores and dumps the value of the chart property object.
Source code in src/ipyvizzu/method.py
class Log(Method):
"""
It stores and dumps the value of the chart property object.
"""
# pylint: disable=too-few-public-methods
def __init__(self, chart_property: ChartProperty):
"""
Log constructor.
Args:
chart_property:
A chart property such as
[CONFIG][ipyvizzu.template.ChartProperty] and
[STYLE][ipyvizzu.template.ChartProperty].
"""
self._data = {"chart_property": chart_property.value}
__init__(chart_property)
Log constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chart_property |
ChartProperty
|
required |
Source code in src/ipyvizzu/method.py
def __init__(self, chart_property: ChartProperty):
"""
Log constructor.
Args:
chart_property:
A chart property such as
[CONFIG][ipyvizzu.template.ChartProperty] and
[STYLE][ipyvizzu.template.ChartProperty].
"""
self._data = {"chart_property": chart_property.value}
ipyvizzu.AnimationControl
A class for controlling animations.
Source code in src/ipyvizzu/animationcontrol.py
class AnimationControl:
"""
A class for controlling animations.
"""
def __init__(self, prev_id: str, last_id: str, display_method: Callable):
"""
AnimationControl constructor.
Args:
prev_id: Id of the previous animation promise.
last_id: Id of the animation to be controlled.
display_method: Displaying function.
"""
self._ids = ", ".join([f"'{prev_id}'", f"'{last_id}'"])
self._display = display_method
def cancel(self) -> None:
"""Cancels the animation, will reject the animation promise."""
self._display(
DisplayTemplate.CONTROL.format(
method="cancel",
params=self._ids,
)
)
def pause(self) -> None:
"""Pauses the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="pause",
params=self._ids,
)
)
def play(self) -> None:
"""Plays/resumes playing of the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="play",
params=self._ids,
)
)
def reverse(self) -> None:
"""Changes the direction of the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="reverse",
params=self._ids,
)
)
def seek(self, value: Union[int, str]) -> None:
"""
Seeks the animation to the position specified by time or progress percentage.
Args:
value: The position specified by time or progress percentage.
"""
params = ", ".join([self._ids, f"'{value}'"])
self._display(
DisplayTemplate.CONTROL.format(
method="seek",
params=params,
)
)
def stop(self) -> None:
"""Stops the current animation seeking it back to its start position."""
self._display(
DisplayTemplate.CONTROL.format(
method="stop",
params=self._ids,
)
)
def store(self) -> Animation:
"""
A method for saving and storing the actual state of the animation.
Returns:
An `Animation` object wich stores the actual state of the animation.
"""
animation_id = uuid.uuid4().hex[:7]
params = ", ".join([self._ids, f"'{animation_id}'"])
self._display(
DisplayTemplate.CONTROL.format(
method="store",
params=params,
)
)
return Animation(animation_id)
__init__(prev_id, last_id, display_method)
AnimationControl constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prev_id |
str
|
Id of the previous animation promise. |
required |
last_id |
str
|
Id of the animation to be controlled. |
required |
display_method |
Callable
|
Displaying function. |
required |
Source code in src/ipyvizzu/animationcontrol.py
def __init__(self, prev_id: str, last_id: str, display_method: Callable):
"""
AnimationControl constructor.
Args:
prev_id: Id of the previous animation promise.
last_id: Id of the animation to be controlled.
display_method: Displaying function.
"""
self._ids = ", ".join([f"'{prev_id}'", f"'{last_id}'"])
self._display = display_method
cancel()
Cancels the animation, will reject the animation promise.
Source code in src/ipyvizzu/animationcontrol.py
def cancel(self) -> None:
"""Cancels the animation, will reject the animation promise."""
self._display(
DisplayTemplate.CONTROL.format(
method="cancel",
params=self._ids,
)
)
pause()
Pauses the controlled animation.
Source code in src/ipyvizzu/animationcontrol.py
def pause(self) -> None:
"""Pauses the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="pause",
params=self._ids,
)
)
play()
Plays/resumes playing of the controlled animation.
Source code in src/ipyvizzu/animationcontrol.py
def play(self) -> None:
"""Plays/resumes playing of the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="play",
params=self._ids,
)
)
reverse()
Changes the direction of the controlled animation.
Source code in src/ipyvizzu/animationcontrol.py
def reverse(self) -> None:
"""Changes the direction of the controlled animation."""
self._display(
DisplayTemplate.CONTROL.format(
method="reverse",
params=self._ids,
)
)
seek(value)
Seeks the animation to the position specified by time or progress percentage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Union[int, str]
|
The position specified by time or progress percentage. |
required |
Source code in src/ipyvizzu/animationcontrol.py
def seek(self, value: Union[int, str]) -> None:
"""
Seeks the animation to the position specified by time or progress percentage.
Args:
value: The position specified by time or progress percentage.
"""
params = ", ".join([self._ids, f"'{value}'"])
self._display(
DisplayTemplate.CONTROL.format(
method="seek",
params=params,
)
)
stop()
Stops the current animation seeking it back to its start position.
Source code in src/ipyvizzu/animationcontrol.py
def stop(self) -> None:
"""Stops the current animation seeking it back to its start position."""
self._display(
DisplayTemplate.CONTROL.format(
method="stop",
params=self._ids,
)
)
store()
A method for saving and storing the actual state of the animation.
Returns:
Type | Description |
---|---|
Animation
|
An |
Source code in src/ipyvizzu/animationcontrol.py
def store(self) -> Animation:
"""
A method for saving and storing the actual state of the animation.
Returns:
An `Animation` object wich stores the actual state of the animation.
"""
animation_id = uuid.uuid4().hex[:7]
params = ", ".join([self._ids, f"'{animation_id}'"])
self._display(
DisplayTemplate.CONTROL.format(
method="store",
params=params,
)
)
return Animation(animation_id)
ipyvizzu.NumpyArrayConverter
Bases: ToSeriesListConverter
Converts a numpy
array
into a list of dictionaries representing series.
Each dictionary contains information about the series name
, values
and type
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
np_array |
array
|
The |
required |
column_name |
Optional[ColumnName]
|
The name of a column. By default, uses column indices. Can be set with an Index:Name pair or, for single-dimensional arrays, with just the Name. |
None
|
column_dtype |
Optional[ColumnDtype]
|
The dtype of a column. By default, uses the np_array's dtype. Can be set with an Index:DType pair or, for single-dimensional arrays, with just the DType. |
None
|
default_measure_value |
MeasureValue
|
Default value to use for missing measure values. Defaults to 0. |
NAN_MEASURE
|
default_dimension_value |
DimensionValue
|
Default value to use for missing dimension values. Defaults to an empty string. |
NAN_DIMENSION
|
Example
Get series list from numpy
array
:
converter = NumpyArrayConverter(np_array)
series_list = converter.get_series_list()
Source code in src/ipyvizzu/data/converters/numpy/converter.py
class NumpyArrayConverter(ToSeriesListConverter):
"""
Converts a `numpy` `array` into a list of dictionaries representing series.
Each dictionary contains information about the series `name`, `values` and `type`.
Parameters:
np_array: The `numpy` `array` to convert.
column_name:
The name of a column. By default, uses column indices. Can be set with an
Index:Name pair or, for single-dimensional arrays, with just the Name.
column_dtype:
The dtype of a column. By default, uses the np_array's dtype. Can be set
with an Index:DType pair or, for single-dimensional arrays, with just the DType.
default_measure_value:
Default value to use for missing measure values. Defaults to 0.
default_dimension_value:
Default value to use for missing dimension values. Defaults to an empty string.
Example:
Get series list from `numpy` `array`:
converter = NumpyArrayConverter(np_array)
series_list = converter.get_series_list()
"""
# pylint: disable=too-few-public-methods
def __init__(
self,
np_array: "numpy.array", # type: ignore
column_name: Optional[ColumnName] = None,
column_dtype: Optional[ColumnDtype] = None,
column_unit: Optional[ColumnUnit] = None,
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
# pylint: disable=too-many-arguments
super().__init__(default_measure_value, default_dimension_value)
self._np = self._get_numpy()
self._np_array = np_array
self._column_name: Dict[Index, Name] = self._get_columns_config(column_name)
self._column_dtype: Dict[Index, DType] = self._get_columns_config(column_dtype)
self._column_unit: Dict[Index, Unit] = self._get_columns_config(column_unit)
def get_series_list(self) -> List[Series]:
"""
Convert the `numpy` `array` to a list of dictionaries representing series.
Returns:
A list of dictionaries representing series,
where each dictionary has `name`, `values` and `type` keys.
"""
if self._np_array.ndim == 0:
return []
if self._np_array.ndim == 1:
return self._get_series_list_from_array1dim()
if self._np_array.ndim == 2:
return self._get_series_list_from_array2dim()
raise ValueError("arrays larger than 2D are not supported")
def _get_series_list_from_array1dim(self) -> List[Series]:
i = 0
name = self._column_name.get(i, i)
unit = self._column_unit.get(i, None)
values, infer_type = self._convert_to_series_values_and_type(
(i, self._np_array)
)
return [self._convert_to_series(name, values, infer_type, unit)]
def _get_series_list_from_array2dim(self) -> List[Series]:
series_list = []
for i in range(self._np_array.shape[1]):
name = self._column_name.get(i, i)
unit = self._column_unit.get(i, None)
values, infer_type = self._convert_to_series_values_and_type(
(i, self._np_array[:, i])
)
series_list.append(self._convert_to_series(name, values, infer_type, unit))
return series_list
def _get_numpy(self) -> ModuleType:
try:
import numpy as np # pylint: disable=import-outside-toplevel
return np
except ImportError as error:
raise ImportError(
"numpy is not available. Please install numpy to use this feature."
) from error
def _get_columns_config(
self,
config: Optional[Union[ColumnConfig, Dict[Index, ColumnConfig]]],
) -> Dict[Index, ColumnConfig]:
if config is None:
return {}
if not isinstance(config, dict):
if not self._np_array.ndim == 1:
raise ValueError("non dict value can only be used for a 1D array")
return {0: config}
return config
def _convert_to_series_values_and_type(
self, obj: Tuple[int, "numpy.array"] # type: ignore
) -> Tuple[SeriesValues, InferType]:
column = obj
i = column[0]
array = column[1]
dtype = self._column_dtype.get(i, self._np_array.dtype)
if self._np.issubdtype(dtype, self._np.number):
return self._convert_to_measure_values(array), InferType.MEASURE
return self._convert_to_dimension_values(array), InferType.DIMENSION
def _convert_to_measure_values(
self, obj: "numpy.array" # type: ignore
) -> List[MeasureValue]:
array = obj
array_float = array.astype(float)
return self._np.nan_to_num(
array_float, nan=self._default_measure_value
).tolist()
def _convert_to_dimension_values(
self, obj: "numpy.array" # type: ignore
) -> List[DimensionValue]:
array = obj
array_str = array.astype(str)
replace_nan = "nan"
mask = array_str == replace_nan
array_str[mask] = self._default_dimension_value
return array_str.tolist()
get_series_list()
Convert the numpy
array
to a list of dictionaries representing series.
Returns:
Type | Description |
---|---|
List[Series]
|
A list of dictionaries representing series, |
List[Series]
|
where each dictionary has |
Source code in src/ipyvizzu/data/converters/numpy/converter.py
def get_series_list(self) -> List[Series]:
"""
Convert the `numpy` `array` to a list of dictionaries representing series.
Returns:
A list of dictionaries representing series,
where each dictionary has `name`, `values` and `type` keys.
"""
if self._np_array.ndim == 0:
return []
if self._np_array.ndim == 1:
return self._get_series_list_from_array1dim()
if self._np_array.ndim == 2:
return self._get_series_list_from_array2dim()
raise ValueError("arrays larger than 2D are not supported")
ipyvizzu.PandasDataFrameConverter
Bases: DataFrameConverter
Converts a pandas
DataFrame
or Series
into a list of dictionaries representing series.
Each dictionary contains information about the series name
, values
and type
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
Union[DataFrame, Series]
|
The |
required |
default_measure_value |
MeasureValue
|
Default value to use for missing measure values. Defaults to 0. |
NAN_MEASURE
|
default_dimension_value |
DimensionValue
|
Default value to use for missing dimension values. Defaults to an empty string. |
NAN_DIMENSION
|
max_rows |
int
|
The maximum number of rows to include in the converted series list.
If the |
MAX_ROWS
|
include_index |
Optional[str]
|
Name for the index column to include as a series. If provided, the index column will be added. Defaults to None. |
None
|
Example
Get series list from DataFrame
columns:
converter = PandasDataFrameConverter(df)
series_list = converter.get_series_list()
Source code in src/ipyvizzu/data/converters/pandas/converter.py
class PandasDataFrameConverter(DataFrameConverter):
"""
Converts a `pandas` `DataFrame` or `Series` into a list of dictionaries representing series.
Each dictionary contains information about the series `name`, `values` and `type`.
Parameters:
df: The `pandas` `DataFrame` or `Series` to convert.
default_measure_value:
Default value to use for missing measure values. Defaults to 0.
default_dimension_value:
Default value to use for missing dimension values. Defaults to an empty string.
max_rows: The maximum number of rows to include in the converted series list.
If the `df` contains more rows,
a random sample of the given number of rows will be taken.
include_index:
Name for the index column to include as a series.
If provided, the index column will be added. Defaults to None.
Example:
Get series list from `DataFrame` columns:
converter = PandasDataFrameConverter(df)
series_list = converter.get_series_list()
"""
def __init__(
self,
df: Union["pandas.DataFrame", "pandas.Series"], # type: ignore
default_measure_value: MeasureValue = NAN_MEASURE,
default_dimension_value: DimensionValue = NAN_DIMENSION,
max_rows: int = MAX_ROWS,
include_index: Optional[str] = None,
units: Optional[Dict[str, str]] = None,
) -> None:
# pylint: disable=too-many-arguments
super().__init__(
default_measure_value, default_dimension_value, max_rows, units
)
self._pd = self._get_pandas()
self._df = self._get_sampled_df(
self._convert_to_df(df) if isinstance(df, PandasSeries) else df
)
self._include_index = include_index
def get_series_list(self) -> List[Series]:
"""
Convert the `DataFrame` columns to a list of dictionaries representing series.
Returns:
A list of dictionaries representing series,
where each dictionary has `name`, `values` and `type` keys.
"""
series_list = super().get_series_list()
index_series = self.get_series_from_index()
return index_series + series_list
def get_series_from_index(self) -> List[Series]:
"""
Convert the `DataFrame` index to a dictionary representing a series,
if `include_index` is provided.
Returns:
A dictionary representing the index series with `name`, `values` and `type` keys.
Returns `None` if `include_index` is not provided.
"""
if not self._include_index or self._df.index.empty:
return []
df = self._pd.DataFrame({self._include_index: self._df.index})
index_series_converter = PandasDataFrameConverter(
df, self._default_measure_value, self._default_dimension_value
)
return index_series_converter.get_series_list()
def _get_pandas(self) -> ModuleType:
try:
import pandas as pd # pylint: disable=import-outside-toplevel
return pd
except ImportError as error:
raise ImportError(
"pandas is not available. Please install pandas to use this feature."
) from error
def _convert_to_df(self, series: "pandas.Series") -> "pandas.Dataframe": # type: ignore
if series.empty:
return self._pd.DataFrame()
return self._pd.DataFrame(series)
def _get_sampled_df(self, df: "pandas.DataFrame") -> "pandas.DataFrame": # type: ignore
row_number = len(df)
if self._is_max_rows_exceeded(row_number):
frac = self._max_rows / row_number
sampled_df = df.sample(
replace=False,
frac=frac,
random_state=42,
)
return sampled_df
return df
def _get_columns(self) -> List[str]:
return self._df.columns
def _convert_to_series_values_and_type(
self, obj: str # type: ignore
) -> Tuple[SeriesValues, InferType]:
column_name = obj
column = self._df[column_name]
if self._pd.api.types.is_numeric_dtype(column.dtype):
return self._convert_to_measure_values(column), InferType.MEASURE
return self._convert_to_dimension_values(column), InferType.DIMENSION
def _convert_to_measure_values(
self, obj: "pandas.DataFrame" # type: ignore
) -> List[MeasureValue]:
column = obj
return column.fillna(self._default_measure_value).astype(float).values.tolist()
def _convert_to_dimension_values(
self, obj: "pandas.DataFrame" # type: ignore
) -> List[DimensionValue]:
column = obj
return column.fillna(self._default_dimension_value).astype(str).values.tolist()
get_series_list()
Convert the DataFrame
columns to a list of dictionaries representing series.
Returns:
Type | Description |
---|---|
List[Series]
|
A list of dictionaries representing series, |
List[Series]
|
where each dictionary has |
Source code in src/ipyvizzu/data/converters/pandas/converter.py
def get_series_list(self) -> List[Series]:
"""
Convert the `DataFrame` columns to a list of dictionaries representing series.
Returns:
A list of dictionaries representing series,
where each dictionary has `name`, `values` and `type` keys.
"""
series_list = super().get_series_list()
index_series = self.get_series_from_index()
return index_series + series_list
get_series_from_index()
Convert the DataFrame
index to a dictionary representing a series,
if include_index
is provided.
Returns:
Type | Description |
---|---|
List[Series]
|
A dictionary representing the index series with |
List[Series]
|
Returns |
Source code in src/ipyvizzu/data/converters/pandas/converter.py
def get_series_from_index(self) -> List[Series]:
"""
Convert the `DataFrame` index to a dictionary representing a series,
if `include_index` is provided.
Returns:
A dictionary representing the index series with `name`, `values` and `type` keys.
Returns `None` if `include_index` is not provided.
"""
if not self._include_index or self._df.index.empty:
return []
df = self._pd.DataFrame({self._include_index: self._df.index})
index_series_converter = PandasDataFrameConverter(
df, self._default_measure_value, self._default_dimension_value
)
return index_series_converter.get_series_list()
ipyvizzu.InferType
Bases: Enum
An enum class for storing data infer types.
Attributes:
Name | Type | Description |
---|---|---|
DIMENSION |
str
|
An enum key-value for storing dimension infer type. Dimensions are categorical series that can contain strings and numbers, but both will be treated as strings. |
MEASURE |
str
|
An enum key-value for storing measure infer type. Measures can only be numerical. |
Source code in src/ipyvizzu/data/infer_type.py
class InferType(Enum):
"""
An enum class for storing data infer types.
Attributes:
DIMENSION: An enum key-value for storing dimension infer type.
Dimensions are categorical series that can contain strings and numbers,
but both will be treated as strings.
MEASURE: An enum key-value for storing measure infer type.
Measures can only be numerical.
"""
DIMENSION: str = "dimension"
MEASURE: str = "measure"
ipyvizzu.Method
A class for dumping chart independent parameters to DisplayTemplate.STORE template.
Source code in src/ipyvizzu/method.py
class Method:
"""
A class for dumping chart independent parameters to
[DisplayTemplate.STORE][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
_data: dict
def dump(self) -> dict:
"""
A method for returning the stored data.
Returns:
The stored data.
"""
return self._data
dump()
A method for returning the stored data.
Returns:
Type | Description |
---|---|
dict
|
The stored data. |
Source code in src/ipyvizzu/method.py
def dump(self) -> dict:
"""
A method for returning the stored data.
Returns:
The stored data.
"""
return self._data
ipyvizzu.EventHandler
A class for representing an event handler.
Source code in src/ipyvizzu/event.py
class EventHandler:
"""A class for representing an event handler."""
def __init__(self, event: str, handler: str):
"""
EventHandler constructor.
It generates a uuid for the event handler,
stores the event type and the body of the handler function.
Args:
event: The type of the event.
handler: The body of the handler function.
"""
self._id = uuid.uuid4().hex[:7]
self._event = event
self._handler = " ".join(handler.split())
@property
def id(self) -> str: # pylint: disable=invalid-name
"""
A property for storing an id.
Returns:
The uuid of the event handler.
"""
return self._id
@property
def event(self) -> str:
"""
A property for storing an event type.
Returns:
The type of the event.
"""
return self._event
@property
def handler(self) -> str:
"""
A property for storing an event handler function.
Returns:
The body of the handler function.
"""
return self._handler
id: str
property
event: str
property
handler: str
property
A property for storing an event handler function.
Returns:
Type | Description |
---|---|
str
|
The body of the handler function. |
__init__(event, handler)
EventHandler constructor.
It generates a uuid for the event handler, stores the event type and the body of the handler function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event |
str
|
The type of the event. |
required |
handler |
str
|
The body of the handler function. |
required |
Source code in src/ipyvizzu/event.py
def __init__(self, event: str, handler: str):
"""
EventHandler constructor.
It generates a uuid for the event handler,
stores the event type and the body of the handler function.
Args:
event: The type of the event.
handler: The body of the handler function.
"""
self._id = uuid.uuid4().hex[:7]
self._event = event
self._handler = " ".join(handler.split())
ipyvizzu.RawJavaScript
A class for representing raw JavaScript code.
Source code in src/ipyvizzu/json.py
class RawJavaScript:
"""A class for representing raw JavaScript code."""
# pylint: disable=too-few-public-methods
def __init__(self, raw: Optional[str]):
"""
RawJavaScript constructor.
It stores raw JavaScript code as a string.
Args:
raw: JavaScript code as `str`.
"""
self._raw = raw
@property
def raw(self) -> Optional[str]:
"""
A property for storing raw JavaScript code as a string.
Returns:
Raw JavaScript code as `str`.
"""
return self._raw
raw: Optional[str]
property
__init__(raw)
RawJavaScript constructor.
It stores raw JavaScript code as a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
raw |
Optional[str]
|
JavaScript code as |
required |
Source code in src/ipyvizzu/json.py
def __init__(self, raw: Optional[str]):
"""
RawJavaScript constructor.
It stores raw JavaScript code as a string.
Args:
raw: JavaScript code as `str`.
"""
self._raw = raw
ipyvizzu.RawJavaScriptEncoder
Bases: JSONEncoder
A class for representing a custom json encoder, it can encode objects that contain RawJavaScript values.
Source code in src/ipyvizzu/json.py
class RawJavaScriptEncoder(json.JSONEncoder):
"""
A class for representing a custom json encoder,
it can encode objects that contain
[RawJavaScript][ipyvizzu.json.RawJavaScript] values.
"""
def __init__(self, *args, **kwargs):
"""
RawJavaScriptEncoder constructor.
It extends [JSONEncoder][json.JSONEncoder] with
an instance variable (`_raw_replacements`).
The `_raw_replacements` dictionary stores the `uuids` and
JavaScript codes of the [RawJavaScript][ipyvizzu.json.RawJavaScript] objects.
"""
json.JSONEncoder.__init__(self, *args, **kwargs)
self._raw_replacements = {}
def default(self, o: Any):
"""
Overrides [JSONEncoder.default][json.JSONEncoder.default] method.
It replaces [RawJavaScript][ipyvizzu.json.RawJavaScript] object with `uuid` and
it stores raw JavaScript code with `uuid` key in the `_raw_replacements` dictionary.
"""
if isinstance(o, RawJavaScript):
key = uuid.uuid4().hex
self._raw_replacements[key] = o.raw
return key
return json.JSONEncoder.default(self, o)
def encode(self, o: Any):
"""
Overrides [JSONEncoder.encode][json.JSONEncoder.encode] method.
It replaces `uuids` with raw JavaScript code without apostrophes.
"""
result = json.JSONEncoder.encode(self, o)
for key, val in self._raw_replacements.items():
result = result.replace(f'"{key}"', val)
return result
__init__(*args, **kwargs)
RawJavaScriptEncoder constructor.
It extends JSONEncoder with
an instance variable (_raw_replacements
).
The _raw_replacements
dictionary stores the uuids
and
JavaScript codes of the RawJavaScript objects.
Source code in src/ipyvizzu/json.py
def __init__(self, *args, **kwargs):
"""
RawJavaScriptEncoder constructor.
It extends [JSONEncoder][json.JSONEncoder] with
an instance variable (`_raw_replacements`).
The `_raw_replacements` dictionary stores the `uuids` and
JavaScript codes of the [RawJavaScript][ipyvizzu.json.RawJavaScript] objects.
"""
json.JSONEncoder.__init__(self, *args, **kwargs)
self._raw_replacements = {}
default(o)
Overrides JSONEncoder.default method.
It replaces RawJavaScript object with uuid
and
it stores raw JavaScript code with uuid
key in the _raw_replacements
dictionary.
Source code in src/ipyvizzu/json.py
def default(self, o: Any):
"""
Overrides [JSONEncoder.default][json.JSONEncoder.default] method.
It replaces [RawJavaScript][ipyvizzu.json.RawJavaScript] object with `uuid` and
it stores raw JavaScript code with `uuid` key in the `_raw_replacements` dictionary.
"""
if isinstance(o, RawJavaScript):
key = uuid.uuid4().hex
self._raw_replacements[key] = o.raw
return key
return json.JSONEncoder.default(self, o)
encode(o)
Overrides JSONEncoder.encode method.
It replaces uuids
with raw JavaScript code without apostrophes.
Source code in src/ipyvizzu/json.py
def encode(self, o: Any):
"""
Overrides [JSONEncoder.encode][json.JSONEncoder.encode] method.
It replaces `uuids` with raw JavaScript code without apostrophes.
"""
result = json.JSONEncoder.encode(self, o)
for key, val in self._raw_replacements.items():
result = result.replace(f'"{key}"', val)
return result
ipyvizzu.ChartProperty
Bases: Enum
An enum class for storing chart properties.
Source code in src/ipyvizzu/template.py
class ChartProperty(Enum):
"""An enum class for storing chart properties."""
CONFIG = "config"
"""An enum key-value for storing config chart property."""
STYLE = "style"
"""An enum key-value for storing style chart property."""
CONFIG = 'config'
class-attribute
instance-attribute
An enum key-value for storing config chart property.
STYLE = 'style'
class-attribute
instance-attribute
An enum key-value for storing style chart property.
ipyvizzu.DisplayTarget
Bases: Enum
An enum class for storing chart display options.
Source code in src/ipyvizzu/template.py
class DisplayTarget(Enum):
"""An enum class for storing chart display options."""
BEGIN = "begin"
"""Display all animation steps after the constructor's cell."""
END = "end"
"""Display all animation steps after the last running cell."""
ACTUAL = "actual"
"""Display the actual animation step after the currently running cell."""
MANUAL = "manual"
"""Display all animation steps after calling a show method."""
BEGIN = 'begin'
class-attribute
instance-attribute
Display all animation steps after the constructor's cell.
END = 'end'
class-attribute
instance-attribute
Display all animation steps after the last running cell.
ACTUAL = 'actual'
class-attribute
instance-attribute
Display the actual animation step after the currently running cell.
MANUAL = 'manual'
class-attribute
instance-attribute
Display all animation steps after calling a show method.
ipyvizzu.DisplayTemplate
A class for storing JavaScript snippet templates.
Source code in src/ipyvizzu/template.py
class DisplayTemplate:
"""A class for storing JavaScript snippet templates."""
# pylint: disable=too-few-public-methods
IPYVIZZUJS: str = "{ipyvizzujs}"
"""ipyvizzu JavaScript class."""
INIT: str = (
"window.ipyvizzu.createChart(element, "
+ "'{chart_id}', '{vizzu}', '{div_width}', '{div_height}');"
)
"""Call createChart JavaScript method."""
CHANGE_ANALYTICS_TO: str = (
"if (window.IpyVizzu) window.IpyVizzu.changeAnalyticsTo({analytics});"
)
"""Call changeAnalyticsTo JavaScript method."""
ANIMATE: str = (
"window.ipyvizzu.animate(element, "
+ "'{chart_id}', '{anim_id}', '{display_target}', {scroll}, "
+ "lib => {{ return {chart_target} }}, {chart_anim_opts});"
)
"""Call animate JavaScript method."""
FEATURE: str = (
"window.ipyvizzu.feature(element, '{chart_id}', '{name}', {enabled});"
)
"""Call feature JavaScript method."""
PLUGIN: str = (
"window.ipyvizzu.plugin(element, "
+ "'{chart_id}', '{plugin}', {options}, '{name}', {enabled});"
)
"""Call plugin JavaScript method."""
STORE: str = "window.ipyvizzu.store(element, '{chart_id}', '{id}');"
"""Call store JavaScript method."""
SET_EVENT: str = (
"window.ipyvizzu.setEvent(element, "
+ "'{chart_id}', '{id}', '{event}', event => {{ {handler} }});"
)
"""Call setEvent JavaScript method."""
CLEAR_EVENT: str = (
"window.ipyvizzu.clearEvent(element, '{chart_id}', '{id}', '{event}');"
)
"""Call clearEvent JavaScript method."""
LOG: str = "window.ipyvizzu.log(element, '{chart_id}', '{chart_property}');"
"""Call log JavaScript method."""
CONTROL: str = "window.ipyvizzu.control(element, '{method}', {params});"
"""Call animation control JavaScript methods."""
CLEAR_INHIBITSCROLL: str = (
"if (window.IpyVizzu) { window.IpyVizzu.clearInhibitScroll(element); }"
)
"""Call clearInhibitScroll JavaScript method if ipyvizzu JavaScript class exists."""
IPYVIZZUJS: str = '{ipyvizzujs}'
class-attribute
instance-attribute
ipyvizzu JavaScript class.
INIT: str = 'window.ipyvizzu.createChart(element, ' + "'{chart_id}', '{vizzu}', '{div_width}', '{div_height}');"
class-attribute
instance-attribute
Call createChart JavaScript method.
CHANGE_ANALYTICS_TO: str = 'if (window.IpyVizzu) window.IpyVizzu.changeAnalyticsTo({analytics});'
class-attribute
instance-attribute
Call changeAnalyticsTo JavaScript method.
ANIMATE: str = 'window.ipyvizzu.animate(element, ' + "'{chart_id}', '{anim_id}', '{display_target}', {scroll}, " + 'lib => {{ return {chart_target} }}, {chart_anim_opts});'
class-attribute
instance-attribute
Call animate JavaScript method.
FEATURE: str = "window.ipyvizzu.feature(element, '{chart_id}', '{name}', {enabled});"
class-attribute
instance-attribute
Call feature JavaScript method.
PLUGIN: str = 'window.ipyvizzu.plugin(element, ' + "'{chart_id}', '{plugin}', {options}, '{name}', {enabled});"
class-attribute
instance-attribute
Call plugin JavaScript method.
STORE: str = "window.ipyvizzu.store(element, '{chart_id}', '{id}');"
class-attribute
instance-attribute
Call store JavaScript method.
SET_EVENT: str = 'window.ipyvizzu.setEvent(element, ' + "'{chart_id}', '{id}', '{event}', event => {{ {handler} }});"
class-attribute
instance-attribute
Call setEvent JavaScript method.
CLEAR_EVENT: str = "window.ipyvizzu.clearEvent(element, '{chart_id}', '{id}', '{event}');"
class-attribute
instance-attribute
Call clearEvent JavaScript method.
LOG: str = "window.ipyvizzu.log(element, '{chart_id}', '{chart_property}');"
class-attribute
instance-attribute
Call log JavaScript method.
CONTROL: str = "window.ipyvizzu.control(element, '{method}', {params});"
class-attribute
instance-attribute
Call animation control JavaScript methods.
CLEAR_INHIBITSCROLL: str = 'if (window.IpyVizzu) { window.IpyVizzu.clearInhibitScroll(element); }'
class-attribute
instance-attribute
Call clearInhibitScroll JavaScript method if ipyvizzu JavaScript class exists.