Skip to content

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:

ipyvizzu.Chart

A class for representing a wrapper over Vizzu chart.

Source code in ipyvizzu/chart.py
class Chart:
    """A class for representing a wrapper over Vizzu chart."""

    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: Optional[str] = VIZZU,
        width: Optional[str] = "800px",
        height: Optional[str] = "480px",
        display: Optional[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 = uuid.uuid4().hex[:7]

        self._display_target = DisplayTarget(display)
        self._calls: List[str] = []
        self._showed = False

        self._scroll_into_view = False

        ipyvizzurawjs = pkgutil.get_data(__name__, "templates/ipyvizzu.js")
        ipyvizzujs = ipyvizzurawjs.decode("utf-8")  # type: ignore
        self._display(DisplayTemplate.IPYVIZZUJS.format(ipyvizzujs=ipyvizzujs))

        self._display(
            DisplayTemplate.INIT.format(
                chart_id=self._chart_id,
                vizzu=vizzu,
                div_width=width,
                div_height=height,
            )
        )

        if self._display_target != DisplayTarget.MANUAL:
            self._register_events()

    @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)

    def animate(
        self, *animations: Animation, **options: Optional[Union[str, int, float, dict]]
    ) -> None:
        """
        A method for changing the state of the chart.

        Args:
            *animations:
                List of Animation 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 = self._merge_animations(animations)
        animate = Animate(animation, options)

        self._display(
            DisplayTemplate.ANIMATE.format(
                display_target=self._display_target.value,
                chart_id=self._chart_id,
                scroll=str(self._scroll_into_view).lower(),
                **animate.dump(),
            )
        )

    @staticmethod
    def _merge_animations(
        animations: Tuple[Animation, ...],
    ) -> Union[Animation, AnimationMerger]:
        if len(animations) == 1:
            return animations[0]

        merger = AnimationMerger()
        for animation in animations:
            merger.merge(animation)

        return merger

    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 animation 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
        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 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

A variable for storing the default url of vizzu package.

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 False).

__init__(vizzu=VIZZU, width='800px', height='480px', display=DisplayTarget.ACTUAL)

Chart constructor.

Parameters:

Name Type Description Default
vizzu Optional[str]

The url of Vizzu JavaScript package.

VIZZU
width Optional[str]

The width of the chart.

'800px'
height Optional[str]

The height of the chart.

'480px'
display Optional[Union[DisplayTarget, str]]

The display behaviour of the chart.

DisplayTarget.ACTUAL
Source code in ipyvizzu/chart.py
def __init__(
    self,
    vizzu: Optional[str] = VIZZU,
    width: Optional[str] = "800px",
    height: Optional[str] = "480px",
    display: Optional[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 = uuid.uuid4().hex[:7]

    self._display_target = DisplayTarget(display)
    self._calls: List[str] = []
    self._showed = False

    self._scroll_into_view = False

    ipyvizzurawjs = pkgutil.get_data(__name__, "templates/ipyvizzu.js")
    ipyvizzujs = ipyvizzurawjs.decode("utf-8")  # type: ignore
    self._display(DisplayTemplate.IPYVIZZUJS.format(ipyvizzujs=ipyvizzujs))

    self._display(
        DisplayTemplate.INIT.format(
            chart_id=self._chart_id,
            vizzu=vizzu,
            div_width=width,
            div_height=height,
        )
    )

    if self._display_target != DisplayTarget.MANUAL:
        self._register_events()

animate(*animations, **options)

A method for changing the state of the chart.

Parameters:

Name Type Description Default
*animations Animation

List of Animation objects such as Data, Config and Style.

()
**options Optional[Union[str, int, float, dict]]

Dictionary of animation options for example duration=1. For information on all available animation options see the Vizzu Code reference.

{}

Raises:

Type Description
ValueError

If animations is not set.

Example

Reset the chart styles:

chart.animate(Style(None))
Source code in ipyvizzu/chart.py
def animate(
    self, *animations: Animation, **options: Optional[Union[str, int, float, dict]]
) -> None:
    """
    A method for changing the state of the chart.

    Args:
        *animations:
            List of Animation 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 = self._merge_animations(animations)
    animate = Animate(animation, options)

    self._display(
        DisplayTemplate.ANIMATE.format(
            display_target=self._display_target.value,
            chart_id=self._chart_id,
            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 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 animation 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 ipyvizzu/chart.py
def store(self) -> Snapshot:
    """
    A method for saving and storing the actual state of the chart.

    Returns:
        A snapshot animation 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 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 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

A chart property such as CONFIG and STYLE.

required
Example

Log the actual style of the chart to the browser console:

chart.log(ChartProperty.STYLE)
Source code in 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 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, Animation

A class for representing data animation. It can build data option of the chart.

Source code in ipyvizzu/animation.py
class Data(dict, Animation):
    """
    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.

Example

Create a Data class with a data filter:

filter = Data.filter("record['Genres'] == 'Pop'")
Source code in 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 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 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 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 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 type keywod argument.

{}
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 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 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 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 data_frame is not instance of pd.DataFrame or pd.Series.

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 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 data_frame is not instance of pd.DataFrame or pd.Series.

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 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 data key whose value is the stored animation.

Source code in 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: Animation

A class for representing config animation. It can build config option of the chart.

Source code in ipyvizzu/animation.py
class Config(Animation, 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 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 config key whose value is the stored animation.

Source code in 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: Animation

A class for representing style animation. It can build style option of the chart.

Source code in ipyvizzu/animation.py
class Style(Animation):
    """
    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 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 style key whose value is the stored animation.

Source code in 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.Snapshot

Bases: Animation

A class for representing snapshot animation. It can build the snapshot id of the chart.

Source code in ipyvizzu/animation.py
class Snapshot(Animation):
    """
    A class for representing snapshot animation.
    It can build the snapshot id of the chart.
    """

    def __init__(self, name: str):
        """
        Snapshot constructor.

        Args:
            name: A snapshot id.
        """

        self._name = name

    def dump(self) -> str:
        """
        A method for overwriting the
        [Animation.dump][ipyvizzu.animation.Animation.dump] method.
        It dumps the stored snapshot id as a string.

        Returns:
            An str that contains the stored snapshot id.
        """

        return f"'{self._name}'"

    def build(self):
        """
        A method for preventing to merge [Snapshot][ipyvizzu.animation.Snapshot]
        with other animations.

        Raises:
            NotImplementedError: If the [build][ipyvizzu.animation.Snapshot.build] method
                has been called, because [Snapshot][ipyvizzu.animation.Snapshot]
                cannot be merged with other animations.
        """

        raise NotImplementedError("Snapshot cannot be merged with other animations")

__init__(name)

Snapshot constructor.

Parameters:

Name Type Description Default
name str

A snapshot id.

required
Source code in ipyvizzu/animation.py
def __init__(self, name: str):
    """
    Snapshot constructor.

    Args:
        name: A snapshot id.
    """

    self._name = name

dump()

A method for overwriting the Animation.dump method. It dumps the stored snapshot id as a string.

Returns:

Type Description
str

An str that contains the stored snapshot id.

Source code in ipyvizzu/animation.py
def dump(self) -> str:
    """
    A method for overwriting the
    [Animation.dump][ipyvizzu.animation.Animation.dump] method.
    It dumps the stored snapshot id as a string.

    Returns:
        An str that contains the stored snapshot id.
    """

    return f"'{self._name}'"

build()

A method for preventing to merge Snapshot with other animations.

Raises:

Type Description
NotImplementedError

If the build method has been called, because Snapshot cannot be merged with other animations.

Source code in ipyvizzu/animation.py
def build(self):
    """
    A method for preventing to merge [Snapshot][ipyvizzu.animation.Snapshot]
    with other animations.

    Raises:
        NotImplementedError: If the [build][ipyvizzu.animation.Snapshot.build] method
            has been called, because [Snapshot][ipyvizzu.animation.Snapshot]
            cannot be merged with other animations.
    """

    raise NotImplementedError("Snapshot cannot be merged with other animations")

ipyvizzu.InferType

Bases: Enum

An enum class for storing data infer types.

Source code in 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

An enum key-value for storing dimension infer type.

MEASURE = 'measure' class-attribute

An enum key-value for storing measure infer type.

ipyvizzu.Animation

An abstract class for representing animation objects that have dump and build methods.

Source code in ipyvizzu/animation.py
class Animation:
    """
    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 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 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, Animation

A class for representing plain animation. It can build any dictionary.

Source code in ipyvizzu/animation.py
class PlainAnimation(dict, Animation):
    """
    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 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: dict, Animation

A class for merging different types of animations.

Source code in ipyvizzu/animation.py
class AnimationMerger(dict, Animation):
    """A class for merging different types of animations."""

    def merge(self, animation: Animation) -> 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.
        """

        data = self._validate(animation)
        self.update(data)

    def _validate(self, animation: Animation) -> dict:
        data = animation.build()
        common_keys = set(data).intersection(self)

        if common_keys:
            raise ValueError(f"Animation is already merged: {common_keys}")

        return data

    def build(self) -> dict:
        """
        A method for returning a merged dictionary from different types of animations.

        Returns:
            A merged dictionary from
                [Data][ipyvizzu.animation.Data],
                [Config][ipyvizzu.animation.Config] and
                [Style][ipyvizzu.animation.Style] animations.
        """

        return self

merge(animation)

A method for merging an animation with the previously merged animations.

Parameters:

Name Type Description Default
animation Animation

An animation to be merged with with previously merged animations.

required

Raises:

Type Description
ValueError

If the type of an animation is already merged.

Source code in ipyvizzu/animation.py
def merge(self, animation: Animation) -> 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.
    """

    data = self._validate(animation)
    self.update(data)

build()

A method for returning a merged dictionary from different types of animations.

Returns:

Type Description
dict

A merged dictionary from Data, Config and Style animations.

Source code in ipyvizzu/animation.py
def build(self) -> dict:
    """
    A method for returning a merged dictionary from different types of animations.

    Returns:
        A merged dictionary from
            [Data][ipyvizzu.animation.Data],
            [Config][ipyvizzu.animation.Config] and
            [Style][ipyvizzu.animation.Style] animations.
    """

    return self

ipyvizzu.Animate

Bases: Method

A class for dumping chart independent parameters to DisplayTemplate.ANIMATE template.

Source code in 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: Union[Animation, AnimationMerger],
        chart_anim_opts: Optional[dict] = None,
    ):
        """
        Animate constructor.

        It stores and dumps `chart_target` and `chart_anim_opts` parameters.

        Args:
            chart_target:
                Animation 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 Union[Animation, AnimationMerger]

Animation object such as Data Config or Style.

required
chart_anim_opts Optional[dict]

Animation options' dictionary. If it is not set, it dumps undefined.

None
Source code in ipyvizzu/method.py
def __init__(
    self,
    chart_target: Union[Animation, AnimationMerger],
    chart_anim_opts: Optional[dict] = None,
):
    """
    Animate constructor.

    It stores and dumps `chart_target` and `chart_anim_opts` parameters.

    Args:
        chart_target:
            Animation 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 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 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 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 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 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 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 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 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 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

A chart property such as CONFIG and STYLE.

required
Source code in 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.Method

A class for storing and dumping any kind of data.

Source code in 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 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 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

A property for storing an id.

Returns:

Type Description
str

The uuid of the event handler.

event: str property

A property for storing an event type.

Returns:

Type Description
str

The type of the event.

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 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 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

A property for storing raw JavaScript code as a string.

Returns:

Type Description
Optional[str]

Raw JavaScript code as str.

__init__(raw)

RawJavaScript constructor.

It stores raw JavaScript code as a string.

Parameters:

Name Type Description Default
raw Optional[str]

JavaScript code as str.

required
Source code in 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 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 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 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 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 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

An enum key-value for storing config chart property.

STYLE = 'style' class-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 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

Display all animation steps after the constructor's cell.

END = 'end' class-attribute

Display all animation steps after the last running cell.

ACTUAL = 'actual' class-attribute

Display the actual animation step after the currently running cell.

MANUAL = 'manual' class-attribute

Display all animation steps after calling a show method.

ipyvizzu.DisplayTemplate

A class for storing JavaScript snippet templates.

Source code in 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}', '{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."""

    CLEAR_INHIBITSCROLL: str = (
        "if (window.IpyVizzu) { window.IpyVizzu.clearInhibitScroll(element); }"
    )
    """Call clearInhibitScroll JavaScript method if ipyvizzu JavaScript class exists."""

IPYVIZZUJS: str = '{ipyvizzujs}' class-attribute

ipyvizzu JavaScript class.

INIT: str = 'window.ipyvizzu.createChart(element, ' + "'{chart_id}', '{vizzu}', '{div_width}', '{div_height}');" class-attribute

Call createChart JavaScript method.

ANIMATE: str = 'window.ipyvizzu.animate(element, ' + "'{chart_id}', '{display_target}', {scroll}, " + 'lib => {{ return {chart_target} }}, {chart_anim_opts});' class-attribute

Call animate JavaScript method.

FEATURE: str = "window.ipyvizzu.feature(element, '{chart_id}', '{name}', {enabled});" class-attribute

Call feature JavaScript method.

STORE: str = "window.ipyvizzu.store(element, '{chart_id}', '{id}');" class-attribute

Call store JavaScript method.

SET_EVENT: str = 'window.ipyvizzu.setEvent(element, ' + "'{chart_id}', '{id}', '{event}', event => {{ {handler} }});" class-attribute

Call setEvent JavaScript method.

CLEAR_EVENT: str = "window.ipyvizzu.clearEvent(element, '{chart_id}', '{id}', '{event}');" class-attribute

Call clearEvent JavaScript method.

LOG: str = "window.ipyvizzu.log(element, '{chart_id}', '{chart_property}');" class-attribute

Call log JavaScript method.

CLEAR_INHIBITSCROLL: str = 'if (window.IpyVizzu) { window.IpyVizzu.clearInhibitScroll(element); }' class-attribute

Call clearInhibitScroll JavaScript method if ipyvizzu JavaScript class exists.