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
- InferType
- AbstractAnimation
- PlainAnimation
- AnimationMerger
- AnimationControl
- 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 = "https://cdn.jsdelivr.net/npm/vizzu@0.7/dist/vizzu.min.js"
"""A variable for storing the default url of 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._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() -> None:
display_javascript(DisplayTemplate.CLEAR_INHIBITSCROLL, raw=True)
@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]):
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
ipyvizzurawjs = pkgutil.get_data(__name__, "templates/ipyvizzu.js")
ipyvizzujs = ipyvizzurawjs.decode("utf-8") # type: ignore
self._display(DisplayTemplate.IPYVIZZUJS.format(ipyvizzujs=ipyvizzujs))
if self._display_target != DisplayTarget.MANUAL:
Chart._register_events()
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/vizzu.Anim.Options/#properties).
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 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/vizzu.Event/#type).
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 = 'https://cdn.jsdelivr.net/npm/vizzu@0.7/dist/vizzu.min.js'
class-attribute
instance-attribute
A variable for storing the default url of vizzu package.
scroll_into_view: bool
writable
property
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. |
DisplayTarget.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._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
ipyvizzurawjs = pkgutil.get_data(__name__, "templates/ipyvizzu.js")
ipyvizzujs = ipyvizzurawjs.decode("utf-8") # type: ignore
self._display(DisplayTemplate.IPYVIZZUJS.format(ipyvizzujs=ipyvizzujs))
if self._display_target != DisplayTarget.MANUAL:
Chart._register_events()
self._display(
DisplayTemplate.INIT.format(
chart_id=self._chart_id,
vizzu=self._vizzu,
div_width=self._width,
div_height=self._height,
)
)
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/vizzu.Anim.Options/#properties).
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(),
)
)
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/vizzu.Event/#type).
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: list) -> 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[list]) -> 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[list] = 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_dimension(self, name: str, values: Optional[list] = 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[list] = 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_data_frame(
self,
data_frame: Union[pd.DataFrame, pd.Series],
default_measure_value: Optional[Any] = 0,
default_dimension_value: Optional[Any] = "",
) -> None:
"""
A method for adding data frame to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame: The pandas data frame object.
default_measure_value: The default measure value to fill the empty values.
default_dimension_value: The default dimension value to fill the empty values.
Raises:
TypeError: If `data_frame` is not instance of [pd.DataFrame][pandas.DataFrame]
or [pd.Series][pandas.Series].
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
data_frame = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_data_frame(data_frame)
"""
if not isinstance(data_frame, type(None)):
if isinstance(data_frame, pd.Series):
data_frame = pd.DataFrame(data_frame)
if not isinstance(data_frame, pd.DataFrame):
raise TypeError(
"data_frame must be instance of pandas.DataFrame or pandas.Series"
)
for name in data_frame.columns:
values = []
if is_numeric_dtype(data_frame[name].dtype):
infer_type = InferType.MEASURE
values = (
data_frame[name]
.fillna(default_measure_value)
.astype(float)
.values.tolist()
)
else:
infer_type = InferType.DIMENSION
values = (
data_frame[name]
.fillna(default_dimension_value)
.astype(str)
.values.tolist()
)
self.add_series(
name,
values,
type=infer_type.value,
)
def add_data_frame_index(
self,
data_frame: Union[pd.DataFrame, pd.Series],
name: Optional[str],
) -> None:
"""
A method for adding data frame's index to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame: The pandas data frame object.
name: The name of the index series.
Raises:
TypeError: If `data_frame` is not instance of [pd.DataFrame][pandas.DataFrame]
or [pd.Series][pandas.Series].
Example:
Adding a data frame's index to a [Data][ipyvizzu.animation.Data] class instance:
data_frame = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_data_frame_index(data_frame, "DataFrameIndex")
data.add_data_frame(data_frame)
"""
if data_frame is not None:
if isinstance(data_frame, pd.Series):
data_frame = pd.DataFrame(data_frame)
if not isinstance(data_frame, pd.DataFrame):
raise TypeError(
"data_frame must be instance of pandas.DataFrame or pandas.Series"
)
self.add_series(
str(name),
[str(i) for i in data_frame.index],
type=InferType.DIMENSION.value,
)
def _add_named_value(
self, dest: str, name: str, values: Optional[list] = None, **kwargs
) -> None:
value = {"name": name, **kwargs}
if values is not None:
value["values"] = values # type: ignore
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 |
list
|
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: list) -> 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[list]
|
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[list]) -> 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[list]
|
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[list] = 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_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]
|
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] = 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[list]
|
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[list] = 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_data_frame(data_frame, default_measure_value=0, default_dimension_value='')
A method for adding data frame to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_frame |
Union[pd.DataFrame, pd.Series]
|
The pandas data frame object. |
required |
default_measure_value |
Optional[Any]
|
The default measure value to fill the empty values. |
0
|
default_dimension_value |
Optional[Any]
|
The default dimension value to fill the empty values. |
''
|
Raises:
Type | Description |
---|---|
TypeError
|
If |
Example
Adding a data frame to a Data class instance:
data_frame = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_data_frame(data_frame)
Source code in src/ipyvizzu/animation.py
def add_data_frame(
self,
data_frame: Union[pd.DataFrame, pd.Series],
default_measure_value: Optional[Any] = 0,
default_dimension_value: Optional[Any] = "",
) -> None:
"""
A method for adding data frame to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame: The pandas data frame object.
default_measure_value: The default measure value to fill the empty values.
default_dimension_value: The default dimension value to fill the empty values.
Raises:
TypeError: If `data_frame` is not instance of [pd.DataFrame][pandas.DataFrame]
or [pd.Series][pandas.Series].
Example:
Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:
data_frame = pd.DataFrame(
{
"Genres": ["Pop", "Rock", "Pop", "Rock"],
"Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
"Popularity": [114, 96, 127, 83],
}
)
data = Data()
data.add_data_frame(data_frame)
"""
if not isinstance(data_frame, type(None)):
if isinstance(data_frame, pd.Series):
data_frame = pd.DataFrame(data_frame)
if not isinstance(data_frame, pd.DataFrame):
raise TypeError(
"data_frame must be instance of pandas.DataFrame or pandas.Series"
)
for name in data_frame.columns:
values = []
if is_numeric_dtype(data_frame[name].dtype):
infer_type = InferType.MEASURE
values = (
data_frame[name]
.fillna(default_measure_value)
.astype(float)
.values.tolist()
)
else:
infer_type = InferType.DIMENSION
values = (
data_frame[name]
.fillna(default_dimension_value)
.astype(str)
.values.tolist()
)
self.add_series(
name,
values,
type=infer_type.value,
)
add_data_frame_index(data_frame, name)
A method for adding data frame's index to an existing Data class instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_frame |
Union[pd.DataFrame, pd.Series]
|
The pandas data frame object. |
required |
name |
Optional[str]
|
The name of the index series. |
required |
Raises:
Type | Description |
---|---|
TypeError
|
If |
Example
Adding a data frame's index to a Data class instance:
data_frame = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_data_frame_index(data_frame, "DataFrameIndex")
data.add_data_frame(data_frame)
Source code in src/ipyvizzu/animation.py
def add_data_frame_index(
self,
data_frame: Union[pd.DataFrame, pd.Series],
name: Optional[str],
) -> None:
"""
A method for adding data frame's index to an existing
[Data][ipyvizzu.animation.Data] class instance.
Args:
data_frame: The pandas data frame object.
name: The name of the index series.
Raises:
TypeError: If `data_frame` is not instance of [pd.DataFrame][pandas.DataFrame]
or [pd.Series][pandas.Series].
Example:
Adding a data frame's index to a [Data][ipyvizzu.animation.Data] class instance:
data_frame = pd.DataFrame(
{"Popularity": [114, 96]},
index=["x", "y"]
)
data = Data()
data.add_data_frame_index(data_frame, "DataFrameIndex")
data.add_data_frame(data_frame)
"""
if data_frame is not None:
if isinstance(data_frame, pd.Series):
data_frame = pd.DataFrame(data_frame)
if not isinstance(data_frame, pd.DataFrame):
raise TypeError(
"data_frame must be instance of pandas.DataFrame or pandas.Series"
)
self.add_series(
str(name),
[str(i) for i in data_frame.index],
type=InferType.DIMENSION.value,
)
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[dict]):
"""
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/vizzu.Config.Chart/#properties).
""" # 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[dict]
|
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[dict]):
"""
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/vizzu.Config.Chart/#properties).
""" # 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/vizzu.Styles.Chart/#properties).
""" # 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/vizzu.Styles.Chart/#properties).
""" # 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/vizzu.Anim.Options/#properties).
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/vizzu.Anim.Options/#properties).
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.InferType
Bases: Enum
An enum class for storing data infer types.
Source code in src/ipyvizzu/animation.py
class InferType(Enum):
"""An enum class for storing data infer types."""
DIMENSION = "dimension"
"""An enum key-value for storing dimension infer type."""
MEASURE = "measure"
"""An enum key-value for storing measure infer type."""
DIMENSION = 'dimension'
class-attribute
instance-attribute
An enum key-value for storing dimension infer type.
MEASURE = 'measure'
class-attribute
instance-attribute
An enum key-value for storing measure infer type.
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):
"""AnimationMerger constructor."""
self._dict = {}
self._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):
"""AnimationMerger constructor."""
self._dict = {}
self._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
A class for dumping chart independent parameters to DisplayTemplate.ANIMATE template.
Source code in src/ipyvizzu/method.py
class Animate(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.ANIMATE][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(
self,
chart_target: AbstractAnimation,
chart_anim_opts: Optional[dict] = None,
):
"""
Animate constructor.
It stores and dumps `chart_target` and `chart_anim_opts` parameters.
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.
It stores and dumps chart_target
and chart_anim_opts
parameters.
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.
It stores and dumps `chart_target` and `chart_anim_opts` parameters.
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
A class for dumping chart independent parameters to DisplayTemplate.FEATURE template.
Source code in src/ipyvizzu/method.py
class Feature(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.FEATURE][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(self, name: str, enabled: bool):
"""
Feature constructor.
It stores and dumps `name` and `enabled` parameters.
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.
It stores and dumps name
and enabled
parameters.
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.
It stores and dumps `name` and `enabled` parameters.
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
A class for dumping chart independent parameters to DisplayTemplate.STORE template.
Source code in src/ipyvizzu/method.py
class Store(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.STORE][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(self, snapshot_id: str):
"""
Store constructor.
It stores and dumps `snapshot_id` parameter.
Args:
snapshot_id: The id of snapshot object.
"""
self._data = {"id": snapshot_id}
__init__(snapshot_id)
Store constructor.
It stores and dumps snapshot_id
parameter.
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.
It stores and dumps `snapshot_id` parameter.
Args:
snapshot_id: The id of snapshot object.
"""
self._data = {"id": snapshot_id}
ipyvizzu.EventOn
Bases: Method
A class for dumping chart independent parameters to DisplayTemplate.SET_EVENT template.
Source code in src/ipyvizzu/method.py
class EventOn(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.SET_EVENT][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(self, event_handler: EventHandler):
"""
EventOn constructor.
It stores and dumps the `id`, the `event` and the `handler` of the event handler object.
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.
It stores and dumps the id
, the event
and the handler
of the event handler object.
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.
It stores and dumps the `id`, the `event` and the `handler` of the event handler object.
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
A class for dumping chart independent parameters to DisplayTemplate.CLEAR_EVENT template.
Source code in src/ipyvizzu/method.py
class EventOff(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.CLEAR_EVENT][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(self, event_handler: EventHandler):
"""
EventOff constructor.
It stores and dumps the `id` and the `event` of the event handler object.
Args:
event_handler: An event handler object.
"""
self._data = {"id": event_handler.id, "event": event_handler.event}
__init__(event_handler)
EventOff constructor.
It stores and dumps the id
and the event
of the event handler object.
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.
It stores and dumps the `id` and the `event` of the event handler object.
Args:
event_handler: An event handler object.
"""
self._data = {"id": event_handler.id, "event": event_handler.event}
ipyvizzu.Log
Bases: Method
A class for dumping chart independent parameters to DisplayTemplate.LOG template.
Source code in src/ipyvizzu/method.py
class Log(Method):
"""
A class for dumping chart independent parameters to
[DisplayTemplate.LOG][ipyvizzu.template.DisplayTemplate] template.
"""
# pylint: disable=too-few-public-methods
def __init__(self, chart_property: ChartProperty):
"""
Log constructor.
It stores and dumps the value of the chart property object.
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.
It stores and dumps the value of the chart property object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chart_property |
ChartProperty
|
required |
Source code in src/ipyvizzu/method.py
def __init__(self, chart_property: ChartProperty):
"""
Log constructor.
It stores and dumps the value of the chart property object.
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.Method
A class for storing and dumping any kind of data.
Source code in src/ipyvizzu/method.py
class Method:
"""A class for storing and dumping any kind of data."""
# 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: json.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):
"""
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):
"""
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):
"""
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):
"""
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."""
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."""
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.
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.
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.