Skip to content

Animation

ipyvizzu.animation

A module for working with chart animations.

ipyvizzu.animation.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.animation.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.animation.Data

Bases: dict, AbstractAnimation

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

Source code in src/ipyvizzu/animation.py
class Data(dict, AbstractAnimation):
    """
    A class for representing data animation.
    It can build data option of the chart.
    """

    @classmethod
    def filter(cls, filter_expr: Optional[str] = None) -> "Data":
        """
        A class method for creating a [Data][ipyvizzu.animation.Data]
        class instance with a data filter.

        Args:
            filter_expr: The JavaScript data filter expression.

        Returns:
            (Data): A data animation instance that contains a data filter.

        Example:
            Create a [Data][ipyvizzu.animation.Data] class with a data filter:

                filter = Data.filter("record['Genres'] == 'Pop'")
        """

        data = cls()
        data.set_filter(filter_expr)
        return data

    def set_filter(self, filter_expr: Optional[str] = None) -> None:
        """
        A method for adding a filter to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            filter_expr: The JavaScript data filter expression.

        Example:
            Add a data filter to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.set_filter("record['Genres'] == 'Pop'")
        """

        filter_expr_raw_js = (
            RawJavaScript(f"record => {{ return ({' '.join(filter_expr.split())}) }}")
            if filter_expr is not None
            else filter_expr
        )
        self.update({"filter": filter_expr_raw_js})

    @classmethod
    def from_json(cls, filename: Union[str, bytes, PathLike]) -> "Data":
        """
        A method for returning a [Data][ipyvizzu.animation.Data]
        class instance which has been created from a json file.

        Args:
            filename: The path of the data source json file.

        Returns:
            (Data): A data animation instance that has been created from a json file.
        """

        with open(filename, "r", encoding="utf8") as file_desc:
            return cls(json.load(file_desc))

    def add_record(self, record: Record) -> None:
        """
        A method for adding a record to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            record: A list that contains data values.

        Example:
            Adding a record to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                record = ["Pop", "Hard", 114]
                data.add_record(record)
        """

        self._add_value("records", record)

    def add_records(self, records: List[Record]) -> None:
        """
        A method for adding records to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            records: A list that contains data records.

        Example:
            Adding records to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                records = [
                    ["Pop", "Hard", 114],
                    ["Rock", "Hard", 96],
                    ["Pop", "Experimental", 127],
                    ["Rock", "Experimental", 83],
                ]
                data.add_records(records)
        """

        list(map(self.add_record, records))

    def add_series(
        self, name: str, values: Optional[SeriesValues] = None, **kwargs
    ) -> None:
        """
        A method for adding a series to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            name: The name of the series.
            values: The data values of the series.
            **kwargs (Optional):
                Arbitrary keyword arguments.

                For example infer type can be set with the `type` keywod argument.

        Example:
            Adding a series without values to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.add_series("Genres")

            Adding a series without values and with infer type to
            a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.add_series("Kinds", type="dimension")

            Adding a series with values to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.add_series(
                    "Popularity", [114, 96, 127, 83]
                )
        """

        self._add_named_value("series", name, values, **kwargs)

    def add_series_list(self, series: List[Series]) -> None:
        """
        A method for adding list of series to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            series: List of series.
        """

        if series:
            self.setdefault("series", []).extend(series)

    def add_dimension(
        self, name: str, values: Optional[List[DimensionValue]] = None, **kwargs
    ) -> None:
        """
        A method for adding a dimension to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            name: The name of the dimension.
            values: The data values of the dimension.
            **kwargs (Optional): Arbitrary keyword arguments.

        Example:
            Adding a dimension with values to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.add_dimension("Genres", ["Pop", "Rock"])
        """

        self._add_named_value("dimensions", name, values, **kwargs)

    def add_measure(
        self, name: str, values: Optional[NestedMeasureValues] = None, **kwargs
    ) -> None:
        """
        A method for adding a measure to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            name: The name of the measure.
            values: The data values of the measure.
            **kwargs (Optional): Arbitrary keyword arguments.

        Example:
            Adding a measure with values to a [Data][ipyvizzu.animation.Data] class instance:

                data = Data()
                data.add_measure(
                    "Popularity",
                    [
                        [114, 96],
                        [127, 83],
                    ],
                )
        """

        self._add_named_value("measures", name, values, **kwargs)

    def add_df(
        self,
        df: Optional[  # type: ignore
            Union[
                "pandas.DataFrame",
                "pandas.Series",
                "pyspark.sql.DataFrame",
            ]
        ],
        default_measure_value: MeasureValue = NAN_MEASURE,
        default_dimension_value: DimensionValue = NAN_DIMENSION,
        max_rows: int = MAX_ROWS,
        include_index: Optional[str] = None,
        units: Optional[Dict[str, str]] = None,
    ) -> None:
        """
        Add a `pandas` `DataFrame`, `Series` or a `pyspark` `DataFrame`
        to an existing [Data][ipyvizzu.animation.Data] class instance.

        Args:
            df:
                The `pandas` `DataFrame`, `Series` or the `pyspark` `DataFrame`to add.
            default_measure_value:
                The default measure value to fill empty values. Defaults to 0.
            default_dimension_value:
                The default dimension value to fill empty values. Defaults to an empty string.
            max_rows:
                The maximum number of rows to include in the converted series list.
                If the `df` contains more rows,
                a random sample of the given number of rows (approximately) will be taken.
            include_index:
                Add the data frame's index as a column with the given name. Defaults to `None`.
                (Cannot be used with `pyspark` `DataFrame`.)
            units:
                A dictionary of column names and units. Defaults to `None`.

        Example:
            Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:

                df = pd.DataFrame(
                    {
                        "Genres": ["Pop", "Rock", "Pop", "Rock"],
                        "Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
                        "Popularity": [114, 96, 127, 83],
                    }
                )
                data = Data()
                data.add_df(df)
        """

        # pylint: disable=too-many-arguments

        if not isinstance(df, type(None)):
            arguments = {
                "df": df,
                "default_measure_value": default_measure_value,
                "default_dimension_value": default_dimension_value,
                "max_rows": max_rows,
                "include_index": include_index,
                "units": units,
            }
            Converter: Union[
                Type[PandasDataFrameConverter], Type[SparkDataFrameConverter]
            ] = PandasDataFrameConverter
            if isinstance(df, SparkDataFrame):
                Converter = SparkDataFrameConverter
                if arguments["include_index"] is not None:
                    raise ValueError(
                        "`include_index` cannot be used with `pyspark` `DataFrame`"
                    )
                del arguments["include_index"]

            converter = Converter(**arguments)  # type: ignore
            series_list = converter.get_series_list()
            self.add_series_list(series_list)

    def add_data_frame(
        self,
        data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
        default_measure_value: MeasureValue = NAN_MEASURE,
        default_dimension_value: DimensionValue = NAN_DIMENSION,
    ) -> None:
        """
        [Deprecated] This function is deprecated and will be removed in future versions.
        Use [add_df][ipyvizzu.animation.Data.add_df] function instead.

        Add a `pandas` `DataFrame` or `Series` to an existing
        [Data][ipyvizzu.animation.Data] class instance.



        Args:
            data_frame:
                The `pandas` `DataFrame` or `Series` to add.
            default_measure_value:
                The default measure value to fill empty values. Defaults to 0.
            default_dimension_value:
                The default dimension value to fill empty values. Defaults to an empty string.
        """

        # pylint: disable=line-too-long

        reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df"
        warnings.warn(
            f"'add_data_frame' is deprecated and will be removed in future versions. Use 'add_df' instead - see {reference}",
            DeprecationWarning,
            stacklevel=2,
        )
        self.add_df(
            data_frame,
            default_measure_value,
            default_dimension_value,
            max_rows=sys.maxsize,
        )

    def add_df_index(
        self,
        df: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
        column_name: str = "Index",
        max_rows: int = MAX_ROWS,
    ) -> None:
        """
        Add the index of a `pandas` `DataFrame` as a series to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            df:
                The `pandas` `DataFrame` or `Series` from which to extract the index.
            column_name:
                Name for the index column to add as a series.
            max_rows:
                The maximum number of rows to include in the converted series list.
                If the `df` contains more rows,
                a random sample of the given number of rows (approximately) will be taken.

        Example:
            Adding a data frame's index to a
            [Data][ipyvizzu.animation.Data] class instance:

                df = pd.DataFrame(
                    {"Popularity": [114, 96]},
                    index=["x", "y"]
                )
                data = Data()
                data.add_df_index(df, "DataFrameIndex")
                data.add_df(df)
        """

        if not isinstance(df, type(None)):
            converter = PandasDataFrameConverter(
                df, max_rows=max_rows, include_index=column_name
            )
            series_list = converter.get_series_from_index()
            self.add_series_list(series_list)

    def add_data_frame_index(
        self,
        data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
        name: str,
    ) -> None:
        """
        [Deprecated] This function is deprecated and will be removed in future versions.
        Use [add_df_index][ipyvizzu.animation.Data.add_df_index] function instead.

        Add the index of a `pandas` `DataFrame` as a series to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            data_frame:
                The `pandas` `DataFrame` or `Series` from which to extract the index.
            name:
                The name of the index series.
        """

        # pylint: disable=line-too-long

        reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df_index"
        warnings.warn(
            f"'add_data_frame_index' is deprecated and will be removed in future versions. Use 'add_df_index' instead - see {reference}",
            DeprecationWarning,
            stacklevel=2,
        )
        self.add_df_index(data_frame, column_name=name, max_rows=sys.maxsize)

    def add_np_array(
        self,
        np_array: Optional["numpy.array"],  # type: ignore
        column_name: Optional[ColumnName] = None,
        column_dtype: Optional[ColumnDtype] = None,
        column_unit: Optional[ColumnUnit] = None,
        default_measure_value: MeasureValue = NAN_MEASURE,
        default_dimension_value: DimensionValue = NAN_DIMENSION,
    ) -> None:
        """
        Add a `numpy` `array` to an existing
        [Data][ipyvizzu.animation.Data] class instance.

        Args:
            np_array: The `numpy` `array` to add.
            column_name:
                The name of a column. By default, uses column indices. Can be set with an
                Index:Name pair or, for single-dimensional arrays, with just the Name.
            column_dtype:
                The dtype of a column. By default, uses the np_array's dtype. Can be set
                with an Index:DType pair or, for single-dimensional arrays, with just the DType.
            default_measure_value:
                Default value to use for missing measure values. Defaults to 0.
            default_dimension_value:
                Default value to use for missing dimension values. Defaults to an empty string.
            column_unit:
                The unit of a column. Defaults to `None`.

        Example:
            Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:

                np_array = np.zeros((3, 4))
                data = Data()
                data.add_np_array(np_array)
        """

        # pylint: disable=too-many-arguments

        if not isinstance(np_array, type(None)):
            converter = NumpyArrayConverter(
                np_array,
                column_name,
                column_dtype,
                column_unit,
                default_measure_value,
                default_dimension_value,
            )
            series_list = converter.get_series_list()
            self.add_series_list(series_list)

    def _add_named_value(
        self,
        dest: str,
        name: str,
        values: Optional[
            Union[
                SeriesValues,
                NestedMeasureValues,
            ]
        ] = None,
        **kwargs,
    ) -> None:
        value = {"name": name, **kwargs}

        if values is not None:
            value["values"] = values

        self._add_value(dest, value)

    def _add_value(self, dest: str, value: Union[dict, list]) -> None:
        self.setdefault(dest, []).append(value)

    def build(self) -> dict:
        """
        A method for validating and returning the data animation dictionary.

        Returns:
            A dictionary that stored in the data animation object.
                It contains a `data` key whose value is the stored animation.
        """

        jsonschema.validate(self, DATA_SCHEMA)
        return {"data": self}

filter(filter_expr=None) classmethod

A class method for creating a Data class instance with a data filter.

Parameters:

Name Type Description Default
filter_expr Optional[str]

The JavaScript data filter expression.

None

Returns:

Type Description
Data

A data animation instance that contains a data filter.

Example

Create a Data class with a data filter:

filter = Data.filter("record['Genres'] == 'Pop'")
Source code in src/ipyvizzu/animation.py
@classmethod
def filter(cls, filter_expr: Optional[str] = None) -> "Data":
    """
    A class method for creating a [Data][ipyvizzu.animation.Data]
    class instance with a data filter.

    Args:
        filter_expr: The JavaScript data filter expression.

    Returns:
        (Data): A data animation instance that contains a data filter.

    Example:
        Create a [Data][ipyvizzu.animation.Data] class with a data filter:

            filter = Data.filter("record['Genres'] == 'Pop'")
    """

    data = cls()
    data.set_filter(filter_expr)
    return data

set_filter(filter_expr=None)

A method for adding a filter to an existing Data class instance.

Parameters:

Name Type Description Default
filter_expr Optional[str]

The JavaScript data filter expression.

None
Example

Add a data filter to a Data class instance:

data = Data()
data.set_filter("record['Genres'] == 'Pop'")
Source code in src/ipyvizzu/animation.py
def set_filter(self, filter_expr: Optional[str] = None) -> None:
    """
    A method for adding a filter to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        filter_expr: The JavaScript data filter expression.

    Example:
        Add a data filter to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.set_filter("record['Genres'] == 'Pop'")
    """

    filter_expr_raw_js = (
        RawJavaScript(f"record => {{ return ({' '.join(filter_expr.split())}) }}")
        if filter_expr is not None
        else filter_expr
    )
    self.update({"filter": filter_expr_raw_js})

from_json(filename) classmethod

A method for returning a Data class instance which has been created from a json file.

Parameters:

Name Type Description Default
filename Union[str, bytes, PathLike]

The path of the data source json file.

required

Returns:

Type Description
Data

A data animation instance that has been created from a json file.

Source code in src/ipyvizzu/animation.py
@classmethod
def from_json(cls, filename: Union[str, bytes, PathLike]) -> "Data":
    """
    A method for returning a [Data][ipyvizzu.animation.Data]
    class instance which has been created from a json file.

    Args:
        filename: The path of the data source json file.

    Returns:
        (Data): A data animation instance that has been created from a json file.
    """

    with open(filename, "r", encoding="utf8") as file_desc:
        return cls(json.load(file_desc))

add_record(record)

A method for adding a record to an existing Data class instance.

Parameters:

Name Type Description Default
record Record

A list that contains data values.

required
Example

Adding a record to a Data class instance:

data = Data()
record = ["Pop", "Hard", 114]
data.add_record(record)
Source code in src/ipyvizzu/animation.py
def add_record(self, record: Record) -> None:
    """
    A method for adding a record to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        record: A list that contains data values.

    Example:
        Adding a record to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            record = ["Pop", "Hard", 114]
            data.add_record(record)
    """

    self._add_value("records", record)

add_records(records)

A method for adding records to an existing Data class instance.

Parameters:

Name Type Description Default
records List[Record]

A list that contains data records.

required
Example

Adding records to a Data class instance:

data = Data()
records = [
    ["Pop", "Hard", 114],
    ["Rock", "Hard", 96],
    ["Pop", "Experimental", 127],
    ["Rock", "Experimental", 83],
]
data.add_records(records)
Source code in src/ipyvizzu/animation.py
def add_records(self, records: List[Record]) -> None:
    """
    A method for adding records to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        records: A list that contains data records.

    Example:
        Adding records to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            records = [
                ["Pop", "Hard", 114],
                ["Rock", "Hard", 96],
                ["Pop", "Experimental", 127],
                ["Rock", "Experimental", 83],
            ]
            data.add_records(records)
    """

    list(map(self.add_record, records))

add_series(name, values=None, **kwargs)

A method for adding a series to an existing Data class instance.

Parameters:

Name Type Description Default
name str

The name of the series.

required
values Optional[SeriesValues]

The data values of the series.

None
**kwargs Optional

Arbitrary keyword arguments.

For example infer type can be set with the 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 src/ipyvizzu/animation.py
def add_series(
    self, name: str, values: Optional[SeriesValues] = None, **kwargs
) -> None:
    """
    A method for adding a series to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        name: The name of the series.
        values: The data values of the series.
        **kwargs (Optional):
            Arbitrary keyword arguments.

            For example infer type can be set with the `type` keywod argument.

    Example:
        Adding a series without values to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.add_series("Genres")

        Adding a series without values and with infer type to
        a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.add_series("Kinds", type="dimension")

        Adding a series with values to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.add_series(
                "Popularity", [114, 96, 127, 83]
            )
    """

    self._add_named_value("series", name, values, **kwargs)

add_series_list(series)

A method for adding list of series to an existing Data class instance.

Parameters:

Name Type Description Default
series List[Series]

List of series.

required
Source code in src/ipyvizzu/animation.py
def add_series_list(self, series: List[Series]) -> None:
    """
    A method for adding list of series to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        series: List of series.
    """

    if series:
        self.setdefault("series", []).extend(series)

add_dimension(name, values=None, **kwargs)

A method for adding a dimension to an existing Data class instance.

Parameters:

Name Type Description Default
name str

The name of the dimension.

required
values Optional[List[DimensionValue]]

The data values of the dimension.

None
**kwargs Optional

Arbitrary keyword arguments.

{}
Example

Adding a dimension with values to a Data class instance:

data = Data()
data.add_dimension("Genres", ["Pop", "Rock"])
Source code in src/ipyvizzu/animation.py
def add_dimension(
    self, name: str, values: Optional[List[DimensionValue]] = None, **kwargs
) -> None:
    """
    A method for adding a dimension to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        name: The name of the dimension.
        values: The data values of the dimension.
        **kwargs (Optional): Arbitrary keyword arguments.

    Example:
        Adding a dimension with values to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.add_dimension("Genres", ["Pop", "Rock"])
    """

    self._add_named_value("dimensions", name, values, **kwargs)

add_measure(name, values=None, **kwargs)

A method for adding a measure to an existing Data class instance.

Parameters:

Name Type Description Default
name str

The name of the measure.

required
values Optional[NestedMeasureValues]

The data values of the measure.

None
**kwargs Optional

Arbitrary keyword arguments.

{}
Example

Adding a measure with values to a Data class instance:

data = Data()
data.add_measure(
    "Popularity",
    [
        [114, 96],
        [127, 83],
    ],
)
Source code in src/ipyvizzu/animation.py
def add_measure(
    self, name: str, values: Optional[NestedMeasureValues] = None, **kwargs
) -> None:
    """
    A method for adding a measure to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        name: The name of the measure.
        values: The data values of the measure.
        **kwargs (Optional): Arbitrary keyword arguments.

    Example:
        Adding a measure with values to a [Data][ipyvizzu.animation.Data] class instance:

            data = Data()
            data.add_measure(
                "Popularity",
                [
                    [114, 96],
                    [127, 83],
                ],
            )
    """

    self._add_named_value("measures", name, values, **kwargs)

add_df(df, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION, max_rows=MAX_ROWS, include_index=None, units=None)

Add a pandas DataFrame, Series or a pyspark DataFrame to an existing Data class instance.

Parameters:

Name Type Description Default
df Optional[Union[DataFrame, Series, DataFrame]]

The pandas DataFrame, Series or the pyspark DataFrameto add.

required
default_measure_value MeasureValue

The default measure value to fill empty values. Defaults to 0.

NAN_MEASURE
default_dimension_value DimensionValue

The default dimension value to fill empty values. Defaults to an empty string.

NAN_DIMENSION
max_rows int

The maximum number of rows to include in the converted series list. If the df contains more rows, a random sample of the given number of rows (approximately) will be taken.

MAX_ROWS
include_index Optional[str]

Add the data frame's index as a column with the given name. Defaults to None. (Cannot be used with pyspark DataFrame.)

None
units Optional[Dict[str, str]]

A dictionary of column names and units. Defaults to None.

None
Example

Adding a data frame to a Data class instance:

df = pd.DataFrame(
    {
        "Genres": ["Pop", "Rock", "Pop", "Rock"],
        "Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
        "Popularity": [114, 96, 127, 83],
    }
)
data = Data()
data.add_df(df)
Source code in src/ipyvizzu/animation.py
def add_df(
    self,
    df: Optional[  # type: ignore
        Union[
            "pandas.DataFrame",
            "pandas.Series",
            "pyspark.sql.DataFrame",
        ]
    ],
    default_measure_value: MeasureValue = NAN_MEASURE,
    default_dimension_value: DimensionValue = NAN_DIMENSION,
    max_rows: int = MAX_ROWS,
    include_index: Optional[str] = None,
    units: Optional[Dict[str, str]] = None,
) -> None:
    """
    Add a `pandas` `DataFrame`, `Series` or a `pyspark` `DataFrame`
    to an existing [Data][ipyvizzu.animation.Data] class instance.

    Args:
        df:
            The `pandas` `DataFrame`, `Series` or the `pyspark` `DataFrame`to add.
        default_measure_value:
            The default measure value to fill empty values. Defaults to 0.
        default_dimension_value:
            The default dimension value to fill empty values. Defaults to an empty string.
        max_rows:
            The maximum number of rows to include in the converted series list.
            If the `df` contains more rows,
            a random sample of the given number of rows (approximately) will be taken.
        include_index:
            Add the data frame's index as a column with the given name. Defaults to `None`.
            (Cannot be used with `pyspark` `DataFrame`.)
        units:
            A dictionary of column names and units. Defaults to `None`.

    Example:
        Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:

            df = pd.DataFrame(
                {
                    "Genres": ["Pop", "Rock", "Pop", "Rock"],
                    "Kinds": ["Hard", "Hard", "Experimental", "Experimental"],
                    "Popularity": [114, 96, 127, 83],
                }
            )
            data = Data()
            data.add_df(df)
    """

    # pylint: disable=too-many-arguments

    if not isinstance(df, type(None)):
        arguments = {
            "df": df,
            "default_measure_value": default_measure_value,
            "default_dimension_value": default_dimension_value,
            "max_rows": max_rows,
            "include_index": include_index,
            "units": units,
        }
        Converter: Union[
            Type[PandasDataFrameConverter], Type[SparkDataFrameConverter]
        ] = PandasDataFrameConverter
        if isinstance(df, SparkDataFrame):
            Converter = SparkDataFrameConverter
            if arguments["include_index"] is not None:
                raise ValueError(
                    "`include_index` cannot be used with `pyspark` `DataFrame`"
                )
            del arguments["include_index"]

        converter = Converter(**arguments)  # type: ignore
        series_list = converter.get_series_list()
        self.add_series_list(series_list)

add_data_frame(data_frame, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION)

[Deprecated] This function is deprecated and will be removed in future versions. Use add_df function instead.

Add a pandas DataFrame or Series to an existing Data class instance.

Parameters:

Name Type Description Default
data_frame Optional[Union[DataFrame, Series]]

The pandas DataFrame or Series to add.

required
default_measure_value MeasureValue

The default measure value to fill empty values. Defaults to 0.

NAN_MEASURE
default_dimension_value DimensionValue

The default dimension value to fill empty values. Defaults to an empty string.

NAN_DIMENSION
Source code in src/ipyvizzu/animation.py
def add_data_frame(
    self,
    data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
    default_measure_value: MeasureValue = NAN_MEASURE,
    default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
    """
    [Deprecated] This function is deprecated and will be removed in future versions.
    Use [add_df][ipyvizzu.animation.Data.add_df] function instead.

    Add a `pandas` `DataFrame` or `Series` to an existing
    [Data][ipyvizzu.animation.Data] class instance.



    Args:
        data_frame:
            The `pandas` `DataFrame` or `Series` to add.
        default_measure_value:
            The default measure value to fill empty values. Defaults to 0.
        default_dimension_value:
            The default dimension value to fill empty values. Defaults to an empty string.
    """

    # pylint: disable=line-too-long

    reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df"
    warnings.warn(
        f"'add_data_frame' is deprecated and will be removed in future versions. Use 'add_df' instead - see {reference}",
        DeprecationWarning,
        stacklevel=2,
    )
    self.add_df(
        data_frame,
        default_measure_value,
        default_dimension_value,
        max_rows=sys.maxsize,
    )

add_df_index(df, column_name='Index', max_rows=MAX_ROWS)

Add the index of a pandas DataFrame as a series to an existing Data class instance.

Parameters:

Name Type Description Default
df Optional[Union[DataFrame, Series]]

The pandas DataFrame or Series from which to extract the index.

required
column_name str

Name for the index column to add as a series.

'Index'
max_rows int

The maximum number of rows to include in the converted series list. If the df contains more rows, a random sample of the given number of rows (approximately) will be taken.

MAX_ROWS
Example

Adding a data frame's index to a Data class instance:

df = pd.DataFrame(
    {"Popularity": [114, 96]},
    index=["x", "y"]
)
data = Data()
data.add_df_index(df, "DataFrameIndex")
data.add_df(df)
Source code in src/ipyvizzu/animation.py
def add_df_index(
    self,
    df: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
    column_name: str = "Index",
    max_rows: int = MAX_ROWS,
) -> None:
    """
    Add the index of a `pandas` `DataFrame` as a series to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        df:
            The `pandas` `DataFrame` or `Series` from which to extract the index.
        column_name:
            Name for the index column to add as a series.
        max_rows:
            The maximum number of rows to include in the converted series list.
            If the `df` contains more rows,
            a random sample of the given number of rows (approximately) will be taken.

    Example:
        Adding a data frame's index to a
        [Data][ipyvizzu.animation.Data] class instance:

            df = pd.DataFrame(
                {"Popularity": [114, 96]},
                index=["x", "y"]
            )
            data = Data()
            data.add_df_index(df, "DataFrameIndex")
            data.add_df(df)
    """

    if not isinstance(df, type(None)):
        converter = PandasDataFrameConverter(
            df, max_rows=max_rows, include_index=column_name
        )
        series_list = converter.get_series_from_index()
        self.add_series_list(series_list)

add_data_frame_index(data_frame, name)

[Deprecated] This function is deprecated and will be removed in future versions. Use add_df_index function instead.

Add the index of a pandas DataFrame as a series to an existing Data class instance.

Parameters:

Name Type Description Default
data_frame Optional[Union[DataFrame, Series]]

The pandas DataFrame or Series from which to extract the index.

required
name str

The name of the index series.

required
Source code in src/ipyvizzu/animation.py
def add_data_frame_index(
    self,
    data_frame: Optional[Union["pandas.DataFrame", "pandas.Series"]],  # type: ignore
    name: str,
) -> None:
    """
    [Deprecated] This function is deprecated and will be removed in future versions.
    Use [add_df_index][ipyvizzu.animation.Data.add_df_index] function instead.

    Add the index of a `pandas` `DataFrame` as a series to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        data_frame:
            The `pandas` `DataFrame` or `Series` from which to extract the index.
        name:
            The name of the index series.
    """

    # pylint: disable=line-too-long

    reference = "https://ipyvizzu.vizzuhq.com/0.17/reference/ipyvizzu/animation/#ipyvizzu.animation.Data.add_df_index"
    warnings.warn(
        f"'add_data_frame_index' is deprecated and will be removed in future versions. Use 'add_df_index' instead - see {reference}",
        DeprecationWarning,
        stacklevel=2,
    )
    self.add_df_index(data_frame, column_name=name, max_rows=sys.maxsize)

add_np_array(np_array, column_name=None, column_dtype=None, column_unit=None, default_measure_value=NAN_MEASURE, default_dimension_value=NAN_DIMENSION)

Add a numpy array to an existing Data class instance.

Parameters:

Name Type Description Default
np_array Optional[array]

The numpy array to add.

required
column_name Optional[ColumnName]

The name of a column. By default, uses column indices. Can be set with an Index:Name pair or, for single-dimensional arrays, with just the Name.

None
column_dtype Optional[ColumnDtype]

The dtype of a column. By default, uses the np_array's dtype. Can be set with an Index:DType pair or, for single-dimensional arrays, with just the DType.

None
default_measure_value MeasureValue

Default value to use for missing measure values. Defaults to 0.

NAN_MEASURE
default_dimension_value DimensionValue

Default value to use for missing dimension values. Defaults to an empty string.

NAN_DIMENSION
column_unit Optional[ColumnUnit]

The unit of a column. Defaults to None.

None
Example

Adding a data frame to a Data class instance:

np_array = np.zeros((3, 4))
data = Data()
data.add_np_array(np_array)
Source code in src/ipyvizzu/animation.py
def add_np_array(
    self,
    np_array: Optional["numpy.array"],  # type: ignore
    column_name: Optional[ColumnName] = None,
    column_dtype: Optional[ColumnDtype] = None,
    column_unit: Optional[ColumnUnit] = None,
    default_measure_value: MeasureValue = NAN_MEASURE,
    default_dimension_value: DimensionValue = NAN_DIMENSION,
) -> None:
    """
    Add a `numpy` `array` to an existing
    [Data][ipyvizzu.animation.Data] class instance.

    Args:
        np_array: The `numpy` `array` to add.
        column_name:
            The name of a column. By default, uses column indices. Can be set with an
            Index:Name pair or, for single-dimensional arrays, with just the Name.
        column_dtype:
            The dtype of a column. By default, uses the np_array's dtype. Can be set
            with an Index:DType pair or, for single-dimensional arrays, with just the DType.
        default_measure_value:
            Default value to use for missing measure values. Defaults to 0.
        default_dimension_value:
            Default value to use for missing dimension values. Defaults to an empty string.
        column_unit:
            The unit of a column. Defaults to `None`.

    Example:
        Adding a data frame to a [Data][ipyvizzu.animation.Data] class instance:

            np_array = np.zeros((3, 4))
            data = Data()
            data.add_np_array(np_array)
    """

    # pylint: disable=too-many-arguments

    if not isinstance(np_array, type(None)):
        converter = NumpyArrayConverter(
            np_array,
            column_name,
            column_dtype,
            column_unit,
            default_measure_value,
            default_dimension_value,
        )
        series_list = converter.get_series_list()
        self.add_series_list(series_list)

build()

A method for validating and returning the data animation dictionary.

Returns:

Type Description
dict

A dictionary that stored in the data animation object. It contains a data key whose value is the stored animation.

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

Bases: type

A metaclass class for the Config class. Returns a Config class with a chart preset if the __getattr__ method called.

For information on all available chart presets see the Vizzu Code reference.

Source code in src/ipyvizzu/animation.py
class ConfigAttr(type):
    """
    A metaclass class for the [Config][ipyvizzu.animation.Config] class.
    Returns a [Config][ipyvizzu.animation.Config] class with a chart preset
    if the `__getattr__` method called.

    For information on all available chart presets see the
    [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/modules/types_presets/).
    """

    @classmethod
    def __getattr__(mcs, name):
        config_attr = mcs("ConfigAttr", (object,), {"name": name})
        return config_attr._get_preset  # pylint: disable=no-member

    def _get_preset(cls, preset):
        config = Config(RawJavaScript(f"lib.presets.{cls.name}({preset})"))
        return config

ipyvizzu.animation.Config

Bases: AbstractAnimation

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

Source code in src/ipyvizzu/animation.py
class Config(AbstractAnimation, metaclass=ConfigAttr):
    """
    A class for representing config animation.
    It can build config option of the chart.
    """

    def __init__(self, data: Optional[Union[dict, RawJavaScript]]):
        """
        Config constructor.

        Args:
            data:
                A config animation dictionary.
                For information on all available config parameters see the
                [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_config.Chart/).
        """  # pylint: disable=line-too-long

        self._data = data

    def build(self) -> dict:
        """
        A method for returning the config animation dictionary.

        Returns:
            A dictionary that stored in the config animation object.
                It contains a `config` key whose value is the stored animation.
        """

        return {"config": self._data}

__init__(data)

Config constructor.

Parameters:

Name Type Description Default
data Optional[Union[dict, RawJavaScript]]

A config animation dictionary. For information on all available config parameters see the Vizzu Code reference.

required
Source code in src/ipyvizzu/animation.py
def __init__(self, data: Optional[Union[dict, RawJavaScript]]):
    """
    Config constructor.

    Args:
        data:
            A config animation dictionary.
            For information on all available config parameters see the
            [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_config.Chart/).
    """  # pylint: disable=line-too-long

    self._data = data

build()

A method for returning the config animation dictionary.

Returns:

Type Description
dict

A dictionary that stored in the config animation object. It contains a config key whose value is the stored animation.

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

Bases: AbstractAnimation

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

Source code in src/ipyvizzu/animation.py
class Style(AbstractAnimation):
    """
    A class for representing style animation.
    It can build style option of the chart.
    """

    def __init__(self, data: Optional[dict]):
        """
        Style constructor.

        Args:
            data:
                A style animation dictionary.
                For information on all available style parameters see the [Style][styling-properties]
                chapter or the
                [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_styles.Chart/).
        """  # pylint: disable=line-too-long

        self._data = data

    def build(self) -> dict:
        """
        A method for returning the style animation dictionary.

        Returns:
            A dictionary that stored in the style animation object.
                It contains a `style` key whose value is the stored animation.
        """

        return {"style": self._data}

__init__(data)

Style constructor.

Parameters:

Name Type Description Default
data Optional[dict]

A style animation dictionary. For information on all available style parameters see the Style chapter or the Vizzu Code reference.

required
Source code in src/ipyvizzu/animation.py
def __init__(self, data: Optional[dict]):
    """
    Style constructor.

    Args:
        data:
            A style animation dictionary.
            For information on all available style parameters see the [Style][styling-properties]
            chapter or the
            [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_styles.Chart/).
    """  # pylint: disable=line-too-long

    self._data = data

build()

A method for returning the style animation dictionary.

Returns:

Type Description
dict

A dictionary that stored in the style animation object. It contains a style key whose value is the stored animation.

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

Bases: AbstractAnimation

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

Source code in src/ipyvizzu/animation.py
class Keyframe(AbstractAnimation):
    """
    A class for representing keyframe animation.
    It can build keyframe of the chart.
    """

    def __init__(
        self,
        *animations: AbstractAnimation,
        **options: Optional[Union[str, int, float, dict]],
    ):
        """
        Keyframe constructor.

        Args:
            *animations:
                List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
                [Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
            **options: Dictionary of animation options for example `duration=1`.
                For information on all available animation options see the
                [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).

        Raises:
            ValueError: If `animations` is not set.
            ValueError: If initialized with a `Keyframe`.
        """  # pylint: disable=line-too-long

        if not animations:
            raise ValueError("No animation was set.")
        if [animation for animation in animations if isinstance(animation, Keyframe)]:
            raise ValueError("A Keyframe cannot contain a Keyframe.")

        self._keyframe = {}
        self._keyframe["target"] = AnimationMerger.merge_animations(animations).build()
        if options:
            self._keyframe["options"] = options

    def build(self) -> dict:
        """
        A method for returning the keyframe animation dictionary.

        Returns:
            A dictionary that stored in the keyframe animation object.
                It contains a `target` key whose value is the stored animation
                and an optional `options` key whose value is the stored animation options.
        """

        return self._keyframe

__init__(*animations, **options)

Keyframe constructor.

Parameters:

Name Type Description Default
*animations AbstractAnimation

List of AbstractAnimation inherited 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.

ValueError

If initialized with a Keyframe.

Source code in src/ipyvizzu/animation.py
def __init__(
    self,
    *animations: AbstractAnimation,
    **options: Optional[Union[str, int, float, dict]],
):
    """
    Keyframe constructor.

    Args:
        *animations:
            List of AbstractAnimation inherited objects such as [Data][ipyvizzu.animation.Data],
            [Config][ipyvizzu.animation.Config] and [Style][ipyvizzu.animation.Style].
        **options: Dictionary of animation options for example `duration=1`.
            For information on all available animation options see the
            [Vizzu Code reference](https://lib.vizzuhq.com/latest/reference/interfaces/types_anim.Options/).

    Raises:
        ValueError: If `animations` is not set.
        ValueError: If initialized with a `Keyframe`.
    """  # pylint: disable=line-too-long

    if not animations:
        raise ValueError("No animation was set.")
    if [animation for animation in animations if isinstance(animation, Keyframe)]:
        raise ValueError("A Keyframe cannot contain a Keyframe.")

    self._keyframe = {}
    self._keyframe["target"] = AnimationMerger.merge_animations(animations).build()
    if options:
        self._keyframe["options"] = options

build()

A method for returning the keyframe animation dictionary.

Returns:

Type Description
dict

A dictionary that stored in the keyframe animation object. It contains a target key whose value is the stored animation and an optional options key whose value is the stored animation options.

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

Bases: AbstractAnimation

A class for merging different types of animations.

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

    def __init__(self) -> None:
        """AnimationMerger constructor."""

        self._dict: dict = {}
        self._list: list = []

    @classmethod
    def merge_animations(
        cls, animations: Tuple[AbstractAnimation, ...]
    ) -> AbstractAnimation:
        """
        A class method for merging animations.

        Args:
            animations: List of `AbstractAnimation` inherited objects.

        Returns:
            An `AnimationMerger` class with the merged animations.
        """

        if len(animations) == 1 and not isinstance(animations[0], Keyframe):
            return animations[0]

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

        return merger

    def merge(self, animation: AbstractAnimation) -> None:
        """
        A method for merging an animation with the previously merged animations.

        Args:
            animation: An animation to be merged with with previously merged animations.

        Raises:
            ValueError: If the type of an animation is already merged.
            ValueError: If `Keyframe` is merged with different type of animation.
        """

        if isinstance(animation, Keyframe):
            if self._dict:
                raise ValueError("Keyframe cannot be merged with other animations.")
            data = animation.build()
            self._list.append(data)
        else:
            if self._list:
                raise ValueError("Keyframe cannot be merged with other animations.")
            data = self._validate(animation)
            self._dict.update(data)

    def _validate(self, animation: AbstractAnimation) -> dict:
        if isinstance(animation, Snapshot):
            raise ValueError("Snapshot cannot be merged with other animations.")
        data = animation.build()
        common_keys = set(data).intersection(self._dict)

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

        return data

    def build(self) -> Union[dict, list]:  # type: ignore
        """
        A method for returning a merged list of `Keyframes`
        or a merged dictionary from different types of animations.

        Returns:
            A merged list of [Keyframes][ipyvizzu.animation.Keyframe] or
                a merged dictionary from
                [Data][ipyvizzu.animation.Data],
                [Config][ipyvizzu.animation.Config] and
                [Style][ipyvizzu.animation.Style] animations.
        """

        if self._dict:
            return self._dict
        return self._list

__init__()

AnimationMerger constructor.

Source code in src/ipyvizzu/animation.py
def __init__(self) -> None:
    """AnimationMerger constructor."""

    self._dict: dict = {}
    self._list: list = []

merge_animations(animations) classmethod

A class method for merging animations.

Parameters:

Name Type Description Default
animations Tuple[AbstractAnimation, ...]

List of AbstractAnimation inherited objects.

required

Returns:

Type Description
AbstractAnimation

An AnimationMerger class with the merged animations.

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 Keyframe is merged with different type of animation.

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]

A merged list of Keyframes or a merged dictionary from Data, Config and Style animations.

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