Skip to content

API Reference

xarray_plotly.xpx(data)

xpx(data: DataArray) -> DataArrayPlotlyAccessor
xpx(data: Dataset) -> DatasetPlotlyAccessor

Get the plotly accessor for a DataArray or Dataset with full IDE code completion.

This is an alternative to da.plotly / ds.plotly that provides proper type hints and code completion in IDEs.

Parameters:

Name Type Description Default
data DataArray | Dataset

The DataArray or Dataset to plot.

required

Returns:

Type Description
DataArrayPlotlyAccessor | DatasetPlotlyAccessor

The accessor with plotting methods (line, bar, area, scatter, box, imshow).

Example
from xarray_plotly import xpx

# DataArray
fig = xpx(da).line()  # Full code completion works here

# Dataset
fig = xpx(ds).line()  # Plots all variables
fig = xpx(ds).line(var="temperature")  # Single variable
Source code in xarray_plotly/__init__.py
def xpx(data: DataArray | Dataset) -> DataArrayPlotlyAccessor | DatasetPlotlyAccessor:
    """Get the plotly accessor for a DataArray or Dataset with full IDE code completion.

    This is an alternative to `da.plotly` / `ds.plotly` that provides proper type hints
    and code completion in IDEs.

    Args:
        data: The DataArray or Dataset to plot.

    Returns:
        The accessor with plotting methods (line, bar, area, scatter, box, imshow).

    Example:
        ```python
        from xarray_plotly import xpx

        # DataArray
        fig = xpx(da).line()  # Full code completion works here

        # Dataset
        fig = xpx(ds).line()  # Plots all variables
        fig = xpx(ds).line(var="temperature")  # Single variable
        ```
    """
    if isinstance(data, Dataset):
        return DatasetPlotlyAccessor(data)
    return DataArrayPlotlyAccessor(data)

xarray_plotly.accessor.DataArrayPlotlyAccessor

Plotly Express plotting accessor for xarray DataArray.

Dimensions are automatically assigned to plot slots by position. All methods return Plotly Figure objects for interactive visualization.

Available methods: line, bar, area, scatter, box, imshow

Parameters:

Name Type Description Default
darray DataArray

The DataArray to plot.

required
Example
import xarray as xr
import numpy as np

da = xr.DataArray(np.random.rand(10, 3), dims=["time", "city"])
fig = da.plotly.line()  # Auto: time->x, city->color
fig = da.plotly.line(color="time", x="city")  # Explicit
fig = da.plotly.line(color=None)  # Skip slot
fig.update_layout(title="My Plot")  # Customize
Source code in xarray_plotly/accessor.py
class DataArrayPlotlyAccessor:
    """Plotly Express plotting accessor for xarray DataArray.

    Dimensions are automatically assigned to plot slots by position.
    All methods return Plotly Figure objects for interactive visualization.

    Available methods: line, bar, area, scatter, box, imshow

    Args:
        darray: The DataArray to plot.

    Example:
        ```python
        import xarray as xr
        import numpy as np

        da = xr.DataArray(np.random.rand(10, 3), dims=["time", "city"])
        fig = da.plotly.line()  # Auto: time->x, city->color
        fig = da.plotly.line(color="time", x="city")  # Explicit
        fig = da.plotly.line(color=None)  # Skip slot
        fig.update_layout(title="My Plot")  # Customize
        ```
    """

    __all__: ClassVar = ["line", "bar", "fast_bar", "area", "scatter", "box", "imshow", "pie"]

    def __init__(self, darray: DataArray) -> None:
        self._da = darray

    def __dir__(self) -> list[str]:
        """List available plot methods."""
        return list(self.__all__) + list(super().__dir__())

    def line(
        self,
        *,
        x: SlotValue = auto,
        color: SlotValue = auto,
        line_dash: SlotValue = auto,
        symbol: SlotValue = auto,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        animation_frame: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive line plot.

        Slot order: x -> color -> line_dash -> symbol -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis. Default: first dimension.
            color: Dimension for color grouping. Default: second dimension.
            line_dash: Dimension for line dash style. Default: third dimension.
            symbol: Dimension for marker symbol. Default: fourth dimension.
            facet_col: Dimension for subplot columns. Default: fifth dimension.
            facet_row: Dimension for subplot rows. Default: sixth dimension.
            animation_frame: Dimension for animation. Default: seventh dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.line()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.line(
            self._da,
            x=x,
            color=color,
            line_dash=line_dash,
            symbol=symbol,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def bar(
        self,
        *,
        x: SlotValue = auto,
        color: SlotValue = auto,
        pattern_shape: SlotValue = auto,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        animation_frame: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive bar chart.

        Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis. Default: first dimension.
            color: Dimension for color grouping. Default: second dimension.
            pattern_shape: Dimension for bar fill pattern. Default: third dimension.
            facet_col: Dimension for subplot columns. Default: fourth dimension.
            facet_row: Dimension for subplot rows. Default: fifth dimension.
            animation_frame: Dimension for animation. Default: sixth dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.bar()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.bar(
            self._da,
            x=x,
            color=color,
            pattern_shape=pattern_shape,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def area(
        self,
        *,
        x: SlotValue = auto,
        color: SlotValue = auto,
        pattern_shape: SlotValue = auto,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        animation_frame: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive stacked area chart.

        Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis. Default: first dimension.
            color: Dimension for color/stacking. Default: second dimension.
            pattern_shape: Dimension for fill pattern. Default: third dimension.
            facet_col: Dimension for subplot columns. Default: fourth dimension.
            facet_row: Dimension for subplot rows. Default: fifth dimension.
            animation_frame: Dimension for animation. Default: sixth dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.area()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.area(
            self._da,
            x=x,
            color=color,
            pattern_shape=pattern_shape,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def fast_bar(
        self,
        *,
        x: SlotValue = auto,
        color: SlotValue = auto,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        animation_frame: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create a bar-like chart using stacked areas for better performance.

        Slot order: x -> color -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis. Default: first dimension.
            color: Dimension for color/stacking. Default: second dimension.
            facet_col: Dimension for subplot columns. Default: third dimension.
            facet_row: Dimension for subplot rows. Default: fourth dimension.
            animation_frame: Dimension for animation. Default: fifth dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.area()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.fast_bar(
            self._da,
            x=x,
            color=color,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def scatter(
        self,
        *,
        x: SlotValue = auto,
        y: SlotValue | str = "value",
        color: SlotValue = auto,
        symbol: SlotValue = auto,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        animation_frame: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive scatter plot.

        By default, y-axis shows the DataArray values. Set y to a dimension
        name to create dimension-vs-dimension plots (e.g., lat vs lon).

        Slot order: x -> color -> symbol -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis. Default: first dimension.
            y: What to plot on y-axis. Default "value" uses DataArray values.
                Can be a dimension name for dimension vs dimension plots.
            color: Dimension for color grouping, or "value" for DataArray values.
            symbol: Dimension for marker symbol. Default: third dimension.
            facet_col: Dimension for subplot columns. Default: fourth dimension.
            facet_row: Dimension for subplot rows. Default: fifth dimension.
            animation_frame: Dimension for animation. Default: sixth dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.scatter()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.scatter(
            self._da,
            x=x,
            y=y,
            color=color,
            symbol=symbol,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def box(
        self,
        *,
        x: SlotValue = auto,
        color: SlotValue = None,
        facet_col: SlotValue = None,
        facet_row: SlotValue = None,
        animation_frame: SlotValue = None,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive box plot.

        By default, only the first dimension is assigned to x; all other
        dimensions are aggregated into the box statistics.

        Slot order: x -> color -> facet_col -> facet_row -> animation_frame

        Args:
            x: Dimension for x-axis categories. Default: first dimension.
            color: Dimension for color grouping. Default: None (aggregated).
            facet_col: Dimension for subplot columns. Default: None (aggregated).
            facet_row: Dimension for subplot rows. Default: None (aggregated).
            animation_frame: Dimension for animation. Default: None (aggregated).
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.box()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.box(
            self._da,
            x=x,
            color=color,
            facet_col=facet_col,
            facet_row=facet_row,
            animation_frame=animation_frame,
            colors=colors,
            **px_kwargs,
        )

    def imshow(
        self,
        *,
        x: SlotValue = auto,
        y: SlotValue = auto,
        facet_col: SlotValue = auto,
        animation_frame: SlotValue = auto,
        robust: bool = False,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive heatmap image.

        Slot order: y (rows) -> x (columns) -> facet_col -> animation_frame

        Note:
            **Difference from px.imshow**: Color bounds are computed from the
            entire dataset by default, ensuring consistent coloring across
            animation frames. Use `zmin`/`zmax` to override.

        Args:
            x: Dimension for x-axis (columns). Default: second dimension.
            y: Dimension for y-axis (rows). Default: first dimension.
            facet_col: Dimension for subplot columns. Default: third dimension.
            animation_frame: Dimension for animation. Default: fourth dimension.
            robust: If True, use 2nd/98th percentiles for color bounds (handles outliers).
            colors: Color scale name (e.g., "Viridis", "RdBu"). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.imshow()`.
                Use `zmin` and `zmax` to manually set color scale bounds.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.imshow(
            self._da,
            x=x,
            y=y,
            facet_col=facet_col,
            animation_frame=animation_frame,
            robust=robust,
            colors=colors,
            **px_kwargs,
        )

    def pie(
        self,
        *,
        names: SlotValue = auto,
        color: SlotValue = None,
        facet_col: SlotValue = auto,
        facet_row: SlotValue = auto,
        colors: Colors = None,
        **px_kwargs: Any,
    ) -> go.Figure:
        """Create an interactive pie chart.

        Slot order: names -> facet_col -> facet_row

        Args:
            names: Dimension for pie slice names/categories. Default: first dimension.
            color: Dimension for color grouping. Default: None (uses names).
            facet_col: Dimension for subplot columns. Default: second dimension.
            facet_row: Dimension for subplot rows. Default: third dimension.
            colors: Color specification (scale name, list, or dict). See module docs.
            **px_kwargs: Additional arguments passed to `plotly.express.pie()`.

        Returns:
            Interactive Plotly Figure.
        """
        return plotting.pie(
            self._da,
            names=names,
            color=color,
            facet_col=facet_col,
            facet_row=facet_row,
            colors=colors,
            **px_kwargs,
        )

line(*, x=auto, color=auto, line_dash=auto, symbol=auto, facet_col=auto, facet_row=auto, animation_frame=auto, colors=None, **px_kwargs)

Create an interactive line plot.

Slot order: x -> color -> line_dash -> symbol -> facet_col -> facet_row -> animation_frame

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis. Default: first dimension.

auto
color SlotValue

Dimension for color grouping. Default: second dimension.

auto
line_dash SlotValue

Dimension for line dash style. Default: third dimension.

auto
symbol SlotValue

Dimension for marker symbol. Default: fourth dimension.

auto
facet_col SlotValue

Dimension for subplot columns. Default: fifth dimension.

auto
facet_row SlotValue

Dimension for subplot rows. Default: sixth dimension.

auto
animation_frame SlotValue

Dimension for animation. Default: seventh dimension.

auto
colors Colors

Color specification (scale name, list, or dict). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.line().

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def line(
    self,
    *,
    x: SlotValue = auto,
    color: SlotValue = auto,
    line_dash: SlotValue = auto,
    symbol: SlotValue = auto,
    facet_col: SlotValue = auto,
    facet_row: SlotValue = auto,
    animation_frame: SlotValue = auto,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive line plot.

    Slot order: x -> color -> line_dash -> symbol -> facet_col -> facet_row -> animation_frame

    Args:
        x: Dimension for x-axis. Default: first dimension.
        color: Dimension for color grouping. Default: second dimension.
        line_dash: Dimension for line dash style. Default: third dimension.
        symbol: Dimension for marker symbol. Default: fourth dimension.
        facet_col: Dimension for subplot columns. Default: fifth dimension.
        facet_row: Dimension for subplot rows. Default: sixth dimension.
        animation_frame: Dimension for animation. Default: seventh dimension.
        colors: Color specification (scale name, list, or dict). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.line()`.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.line(
        self._da,
        x=x,
        color=color,
        line_dash=line_dash,
        symbol=symbol,
        facet_col=facet_col,
        facet_row=facet_row,
        animation_frame=animation_frame,
        colors=colors,
        **px_kwargs,
    )

bar(*, x=auto, color=auto, pattern_shape=auto, facet_col=auto, facet_row=auto, animation_frame=auto, colors=None, **px_kwargs)

Create an interactive bar chart.

Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis. Default: first dimension.

auto
color SlotValue

Dimension for color grouping. Default: second dimension.

auto
pattern_shape SlotValue

Dimension for bar fill pattern. Default: third dimension.

auto
facet_col SlotValue

Dimension for subplot columns. Default: fourth dimension.

auto
facet_row SlotValue

Dimension for subplot rows. Default: fifth dimension.

auto
animation_frame SlotValue

Dimension for animation. Default: sixth dimension.

auto
colors Colors

Color specification (scale name, list, or dict). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.bar().

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def bar(
    self,
    *,
    x: SlotValue = auto,
    color: SlotValue = auto,
    pattern_shape: SlotValue = auto,
    facet_col: SlotValue = auto,
    facet_row: SlotValue = auto,
    animation_frame: SlotValue = auto,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive bar chart.

    Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

    Args:
        x: Dimension for x-axis. Default: first dimension.
        color: Dimension for color grouping. Default: second dimension.
        pattern_shape: Dimension for bar fill pattern. Default: third dimension.
        facet_col: Dimension for subplot columns. Default: fourth dimension.
        facet_row: Dimension for subplot rows. Default: fifth dimension.
        animation_frame: Dimension for animation. Default: sixth dimension.
        colors: Color specification (scale name, list, or dict). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.bar()`.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.bar(
        self._da,
        x=x,
        color=color,
        pattern_shape=pattern_shape,
        facet_col=facet_col,
        facet_row=facet_row,
        animation_frame=animation_frame,
        colors=colors,
        **px_kwargs,
    )

area(*, x=auto, color=auto, pattern_shape=auto, facet_col=auto, facet_row=auto, animation_frame=auto, colors=None, **px_kwargs)

Create an interactive stacked area chart.

Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis. Default: first dimension.

auto
color SlotValue

Dimension for color/stacking. Default: second dimension.

auto
pattern_shape SlotValue

Dimension for fill pattern. Default: third dimension.

auto
facet_col SlotValue

Dimension for subplot columns. Default: fourth dimension.

auto
facet_row SlotValue

Dimension for subplot rows. Default: fifth dimension.

auto
animation_frame SlotValue

Dimension for animation. Default: sixth dimension.

auto
colors Colors

Color specification (scale name, list, or dict). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.area().

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def area(
    self,
    *,
    x: SlotValue = auto,
    color: SlotValue = auto,
    pattern_shape: SlotValue = auto,
    facet_col: SlotValue = auto,
    facet_row: SlotValue = auto,
    animation_frame: SlotValue = auto,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive stacked area chart.

    Slot order: x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame

    Args:
        x: Dimension for x-axis. Default: first dimension.
        color: Dimension for color/stacking. Default: second dimension.
        pattern_shape: Dimension for fill pattern. Default: third dimension.
        facet_col: Dimension for subplot columns. Default: fourth dimension.
        facet_row: Dimension for subplot rows. Default: fifth dimension.
        animation_frame: Dimension for animation. Default: sixth dimension.
        colors: Color specification (scale name, list, or dict). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.area()`.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.area(
        self._da,
        x=x,
        color=color,
        pattern_shape=pattern_shape,
        facet_col=facet_col,
        facet_row=facet_row,
        animation_frame=animation_frame,
        colors=colors,
        **px_kwargs,
    )

scatter(*, x=auto, y='value', color=auto, symbol=auto, facet_col=auto, facet_row=auto, animation_frame=auto, colors=None, **px_kwargs)

Create an interactive scatter plot.

By default, y-axis shows the DataArray values. Set y to a dimension name to create dimension-vs-dimension plots (e.g., lat vs lon).

Slot order: x -> color -> symbol -> facet_col -> facet_row -> animation_frame

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis. Default: first dimension.

auto
y SlotValue | str

What to plot on y-axis. Default "value" uses DataArray values. Can be a dimension name for dimension vs dimension plots.

'value'
color SlotValue

Dimension for color grouping, or "value" for DataArray values.

auto
symbol SlotValue

Dimension for marker symbol. Default: third dimension.

auto
facet_col SlotValue

Dimension for subplot columns. Default: fourth dimension.

auto
facet_row SlotValue

Dimension for subplot rows. Default: fifth dimension.

auto
animation_frame SlotValue

Dimension for animation. Default: sixth dimension.

auto
colors Colors

Color specification (scale name, list, or dict). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.scatter().

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def scatter(
    self,
    *,
    x: SlotValue = auto,
    y: SlotValue | str = "value",
    color: SlotValue = auto,
    symbol: SlotValue = auto,
    facet_col: SlotValue = auto,
    facet_row: SlotValue = auto,
    animation_frame: SlotValue = auto,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive scatter plot.

    By default, y-axis shows the DataArray values. Set y to a dimension
    name to create dimension-vs-dimension plots (e.g., lat vs lon).

    Slot order: x -> color -> symbol -> facet_col -> facet_row -> animation_frame

    Args:
        x: Dimension for x-axis. Default: first dimension.
        y: What to plot on y-axis. Default "value" uses DataArray values.
            Can be a dimension name for dimension vs dimension plots.
        color: Dimension for color grouping, or "value" for DataArray values.
        symbol: Dimension for marker symbol. Default: third dimension.
        facet_col: Dimension for subplot columns. Default: fourth dimension.
        facet_row: Dimension for subplot rows. Default: fifth dimension.
        animation_frame: Dimension for animation. Default: sixth dimension.
        colors: Color specification (scale name, list, or dict). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.scatter()`.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.scatter(
        self._da,
        x=x,
        y=y,
        color=color,
        symbol=symbol,
        facet_col=facet_col,
        facet_row=facet_row,
        animation_frame=animation_frame,
        colors=colors,
        **px_kwargs,
    )

box(*, x=auto, color=None, facet_col=None, facet_row=None, animation_frame=None, colors=None, **px_kwargs)

Create an interactive box plot.

By default, only the first dimension is assigned to x; all other dimensions are aggregated into the box statistics.

Slot order: x -> color -> facet_col -> facet_row -> animation_frame

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis categories. Default: first dimension.

auto
color SlotValue

Dimension for color grouping. Default: None (aggregated).

None
facet_col SlotValue

Dimension for subplot columns. Default: None (aggregated).

None
facet_row SlotValue

Dimension for subplot rows. Default: None (aggregated).

None
animation_frame SlotValue

Dimension for animation. Default: None (aggregated).

None
colors Colors

Color specification (scale name, list, or dict). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.box().

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def box(
    self,
    *,
    x: SlotValue = auto,
    color: SlotValue = None,
    facet_col: SlotValue = None,
    facet_row: SlotValue = None,
    animation_frame: SlotValue = None,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive box plot.

    By default, only the first dimension is assigned to x; all other
    dimensions are aggregated into the box statistics.

    Slot order: x -> color -> facet_col -> facet_row -> animation_frame

    Args:
        x: Dimension for x-axis categories. Default: first dimension.
        color: Dimension for color grouping. Default: None (aggregated).
        facet_col: Dimension for subplot columns. Default: None (aggregated).
        facet_row: Dimension for subplot rows. Default: None (aggregated).
        animation_frame: Dimension for animation. Default: None (aggregated).
        colors: Color specification (scale name, list, or dict). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.box()`.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.box(
        self._da,
        x=x,
        color=color,
        facet_col=facet_col,
        facet_row=facet_row,
        animation_frame=animation_frame,
        colors=colors,
        **px_kwargs,
    )

imshow(*, x=auto, y=auto, facet_col=auto, animation_frame=auto, robust=False, colors=None, **px_kwargs)

Create an interactive heatmap image.

Slot order: y (rows) -> x (columns) -> facet_col -> animation_frame

Note

Difference from px.imshow: Color bounds are computed from the entire dataset by default, ensuring consistent coloring across animation frames. Use zmin/zmax to override.

Parameters:

Name Type Description Default
x SlotValue

Dimension for x-axis (columns). Default: second dimension.

auto
y SlotValue

Dimension for y-axis (rows). Default: first dimension.

auto
facet_col SlotValue

Dimension for subplot columns. Default: third dimension.

auto
animation_frame SlotValue

Dimension for animation. Default: fourth dimension.

auto
robust bool

If True, use 2nd/98th percentiles for color bounds (handles outliers).

False
colors Colors

Color scale name (e.g., "Viridis", "RdBu"). See module docs.

None
**px_kwargs Any

Additional arguments passed to plotly.express.imshow(). Use zmin and zmax to manually set color scale bounds.

{}

Returns:

Type Description
Figure

Interactive Plotly Figure.

Source code in xarray_plotly/accessor.py
def imshow(
    self,
    *,
    x: SlotValue = auto,
    y: SlotValue = auto,
    facet_col: SlotValue = auto,
    animation_frame: SlotValue = auto,
    robust: bool = False,
    colors: Colors = None,
    **px_kwargs: Any,
) -> go.Figure:
    """Create an interactive heatmap image.

    Slot order: y (rows) -> x (columns) -> facet_col -> animation_frame

    Note:
        **Difference from px.imshow**: Color bounds are computed from the
        entire dataset by default, ensuring consistent coloring across
        animation frames. Use `zmin`/`zmax` to override.

    Args:
        x: Dimension for x-axis (columns). Default: second dimension.
        y: Dimension for y-axis (rows). Default: first dimension.
        facet_col: Dimension for subplot columns. Default: third dimension.
        animation_frame: Dimension for animation. Default: fourth dimension.
        robust: If True, use 2nd/98th percentiles for color bounds (handles outliers).
        colors: Color scale name (e.g., "Viridis", "RdBu"). See module docs.
        **px_kwargs: Additional arguments passed to `plotly.express.imshow()`.
            Use `zmin` and `zmax` to manually set color scale bounds.

    Returns:
        Interactive Plotly Figure.
    """
    return plotting.imshow(
        self._da,
        x=x,
        y=y,
        facet_col=facet_col,
        animation_frame=animation_frame,
        robust=robust,
        colors=colors,
        **px_kwargs,
    )

xarray_plotly.config

Configuration for xarray_plotly.

This module provides a global configuration system similar to xarray and pandas, allowing users to customize label extraction and slot assignment behavior.

Options dataclass

Configuration options for xarray_plotly.

Attributes:

Name Type Description
label_use_long_name bool

Use long_name attribute for labels. Default True.

label_use_standard_name bool

Fall back to standard_name if long_name not available.

label_include_units bool

Append units to labels. Default True.

label_unit_format str

Format string for units. Use {units} as placeholder.

slot_orders dict[str, tuple[str, ...]]

Slot orders per plot type. Keys are plot types, values are tuples.

dataset_variable_position int

Position of "variable" dim when plotting all Dataset variables. Default 1 (second position, typically color). Set to 0 for first position (x-axis), or -1 for last position.

Source code in xarray_plotly/config.py
@dataclass
class Options:
    """Configuration options for xarray_plotly.

    Attributes:
        label_use_long_name: Use `long_name` attribute for labels. Default True.
        label_use_standard_name: Fall back to `standard_name` if `long_name` not available.
        label_include_units: Append units to labels. Default True.
        label_unit_format: Format string for units. Use `{units}` as placeholder.
        slot_orders: Slot orders per plot type. Keys are plot types, values are tuples.
        dataset_variable_position: Position of "variable" dim when plotting all Dataset
            variables. Default 1 (second position, typically color). Set to 0 for first
            position (x-axis), or -1 for last position.
    """

    label_use_long_name: bool = True
    label_use_standard_name: bool = True
    label_include_units: bool = True
    label_unit_format: str = "[{units}]"
    slot_orders: dict[str, tuple[str, ...]] = field(
        default_factory=lambda: dict(DEFAULT_SLOT_ORDERS)
    )
    dataset_variable_position: int = 1

    def to_dict(self) -> dict[str, Any]:
        """Return options as a dictionary."""
        return {
            "label_use_long_name": self.label_use_long_name,
            "label_use_standard_name": self.label_use_standard_name,
            "label_include_units": self.label_include_units,
            "label_unit_format": self.label_unit_format,
            "slot_orders": self.slot_orders,
            "dataset_variable_position": self.dataset_variable_position,
        }

to_dict()

Return options as a dictionary.

Source code in xarray_plotly/config.py
def to_dict(self) -> dict[str, Any]:
    """Return options as a dictionary."""
    return {
        "label_use_long_name": self.label_use_long_name,
        "label_use_standard_name": self.label_use_standard_name,
        "label_include_units": self.label_include_units,
        "label_unit_format": self.label_unit_format,
        "slot_orders": self.slot_orders,
        "dataset_variable_position": self.dataset_variable_position,
    }

notebook(renderer='notebook')

Configure Plotly for Jupyter notebook rendering.

Parameters:

Name Type Description Default
renderer str

The Plotly renderer to use. Default is "notebook". Other options include "jupyterlab", "colab", "kaggle", etc.

'notebook'
Example
from xarray_plotly import config
config.notebook()  # Configure for Jupyter notebooks
Source code in xarray_plotly/config.py
def notebook(renderer: str = "notebook") -> None:
    """Configure Plotly for Jupyter notebook rendering.

    Args:
        renderer: The Plotly renderer to use. Default is "notebook".
            Other options include "jupyterlab", "colab", "kaggle", etc.

    Example:
        ```python
        from xarray_plotly import config
        config.notebook()  # Configure for Jupyter notebooks
        ```
    """
    import plotly.io as pio

    pio.renderers.default = renderer

get_options()

Get the current xarray_plotly options.

Returns:

Type Description
dict[str, Any]

Dictionary of current option values.

Example
from xarray_plotly import config
config.get_options()
Source code in xarray_plotly/config.py
def get_options() -> dict[str, Any]:
    """Get the current xarray_plotly options.

    Returns:
        Dictionary of current option values.

    Example:
        ```python
        from xarray_plotly import config
        config.get_options()
        ```
    """
    return _options.to_dict()

set_options(*, label_use_long_name=None, label_use_standard_name=None, label_include_units=None, label_unit_format=None, slot_orders=None, dataset_variable_position=None)

Set xarray_plotly options globally or as a context manager.

Parameters:

Name Type Description Default
label_use_long_name bool | None

Use long_name attribute for labels.

None
label_use_standard_name bool | None

Fall back to standard_name if long_name not available.

None
label_include_units bool | None

Append units to labels.

None
label_unit_format str | None

Format string for units. Use {units} as placeholder.

None
slot_orders dict[str, tuple[str, ...]] | None

Slot orders per plot type.

None
dataset_variable_position int | None

Position of "variable" dim when plotting all Dataset variables. Default 1 (second, typically color). Use 0 for first, -1 for last.

None

Yields:

Type Description
None

None when used as a context manager.

Example
from xarray_plotly import config, xpx

# Use as context manager
with config.set_options(label_include_units=False):
    fig = xpx(da).line()  # No units in labels
# Units are back after the context
Source code in xarray_plotly/config.py
@contextmanager
def set_options(
    *,
    label_use_long_name: bool | None = None,
    label_use_standard_name: bool | None = None,
    label_include_units: bool | None = None,
    label_unit_format: str | None = None,
    slot_orders: dict[str, tuple[str, ...]] | None = None,
    dataset_variable_position: int | None = None,
) -> Generator[None, None, None]:
    """Set xarray_plotly options globally or as a context manager.

    Args:
        label_use_long_name: Use `long_name` attribute for labels.
        label_use_standard_name: Fall back to `standard_name` if `long_name` not available.
        label_include_units: Append units to labels.
        label_unit_format: Format string for units. Use `{units}` as placeholder.
        slot_orders: Slot orders per plot type.
        dataset_variable_position: Position of "variable" dim when plotting all Dataset
            variables. Default 1 (second, typically color). Use 0 for first, -1 for last.

    Yields:
        None when used as a context manager.

    Example:
        ```python
        from xarray_plotly import config, xpx

        # Use as context manager
        with config.set_options(label_include_units=False):
            fig = xpx(da).line()  # No units in labels
        # Units are back after the context
        ```
    """
    # Store old values
    old_values = {
        "label_use_long_name": _options.label_use_long_name,
        "label_use_standard_name": _options.label_use_standard_name,
        "label_include_units": _options.label_include_units,
        "label_unit_format": _options.label_unit_format,
        "slot_orders": dict(_options.slot_orders),
        "dataset_variable_position": _options.dataset_variable_position,
    }

    # Apply new values (modify in place to keep reference)
    if label_use_long_name is not None:
        _options.label_use_long_name = label_use_long_name
    if label_use_standard_name is not None:
        _options.label_use_standard_name = label_use_standard_name
    if label_include_units is not None:
        _options.label_include_units = label_include_units
    if label_unit_format is not None:
        _options.label_unit_format = label_unit_format
    if slot_orders is not None:
        _options.slot_orders = dict(slot_orders)
    if dataset_variable_position is not None:
        _options.dataset_variable_position = dataset_variable_position

    try:
        yield
    finally:
        # Restore old values (modify in place)
        _options.label_use_long_name = cast("bool", old_values["label_use_long_name"])
        _options.label_use_standard_name = cast("bool", old_values["label_use_standard_name"])
        _options.label_include_units = cast("bool", old_values["label_include_units"])
        _options.label_unit_format = cast("str", old_values["label_unit_format"])
        _options.slot_orders = cast("dict[str, tuple[str, ...]]", old_values["slot_orders"])
        _options.dataset_variable_position = cast("int", old_values["dataset_variable_position"])

xarray_plotly.common

Common utilities for dimension-to-slot assignment and data conversion.

auto = _AUTO() module-attribute

SLOT_ORDERS = DEFAULT_SLOT_ORDERS module-attribute

Slot orders per plot type.

For most plots, y-axis shows DataArray values (not a dimension slot). For imshow, both y and x are dimensions (rows and columns of the heatmap).

Note

To customize slot orders, use config.set_options(slot_orders=...).

assign_slots(dims, plot_type, *, allow_unassigned=False, **slot_kwargs)

Assign dimensions to plot slots based on position.

Positional assignment: dimensions fill slots in order. - Explicit assignments lock a dimension to a slot - None skips a slot - Remaining dims fill remaining slots by position - Error if dims left over after all slots filled (unless allow_unassigned=True)

Parameters:

Name Type Description Default
dims Sequence[Hashable]

Dimension names from the DataArray.

required
plot_type str

Type of plot (line, bar, area, scatter, box, imshow).

required
allow_unassigned bool

If True, allow dimensions to remain unassigned.

False
**slot_kwargs SlotValue

Explicit slot assignments. Use auto for positional, a dimension name for explicit, or None to skip.

{}

Returns:

Type Description
dict[str, Hashable]

Mapping of slot names to dimension names.

Raises:

Type Description
ValueError

If plot_type is unknown, dimension doesn't exist, or dimensions are left unassigned (unless allow_unassigned=True).

Example
assign_slots(["time", "city", "scenario"], "line")
# {'x': 'time', 'color': 'city', 'line_dash': 'scenario'}

assign_slots(["time", "city"], "line", color="time", x="city")
# {'x': 'city', 'color': 'time'}

assign_slots(["time", "city", "scenario"], "line", color=None)
# {'x': 'time', 'line_dash': 'city', 'symbol': 'scenario'}
Source code in xarray_plotly/common.py
def assign_slots(
    dims: Sequence[Hashable],
    plot_type: str,
    *,
    allow_unassigned: bool = False,
    **slot_kwargs: SlotValue,
) -> dict[str, Hashable]:
    """Assign dimensions to plot slots based on position.

    Positional assignment: dimensions fill slots in order.
    - Explicit assignments lock a dimension to a slot
    - None skips a slot
    - Remaining dims fill remaining slots by position
    - Error if dims left over after all slots filled (unless allow_unassigned=True)

    Args:
        dims: Dimension names from the DataArray.
        plot_type: Type of plot (line, bar, area, scatter, box, imshow).
        allow_unassigned: If True, allow dimensions to remain unassigned.
        **slot_kwargs: Explicit slot assignments. Use `auto` for positional,
            a dimension name for explicit, or `None` to skip.

    Returns:
        Mapping of slot names to dimension names.

    Raises:
        ValueError: If plot_type is unknown, dimension doesn't exist, or
            dimensions are left unassigned (unless allow_unassigned=True).

    Example:
        ```python
        assign_slots(["time", "city", "scenario"], "line")
        # {'x': 'time', 'color': 'city', 'line_dash': 'scenario'}

        assign_slots(["time", "city"], "line", color="time", x="city")
        # {'x': 'city', 'color': 'time'}

        assign_slots(["time", "city", "scenario"], "line", color=None)
        # {'x': 'time', 'line_dash': 'city', 'symbol': 'scenario'}
        ```
    """
    slot_orders = _options.slot_orders
    if plot_type not in slot_orders:
        msg = f"Unknown plot type: {plot_type!r}. Available types: {list(slot_orders.keys())}"
        raise ValueError(msg)

    slot_order = slot_orders[plot_type]
    dims_list = list(dims)

    slots: dict[str, Hashable] = {}
    used_dims: set[Hashable] = set()
    available_slots = list(slot_order)

    # Pass 1: Process explicit assignments (non-auto, non-None)
    for slot in slot_order:
        value = slot_kwargs.get(slot, auto)

        if value is None:
            # Skip this slot
            if slot in available_slots:
                available_slots.remove(slot)
        elif not isinstance(value, _AUTO):
            # Explicit assignment - can be a dimension name or "value" (DataArray values)
            if value == "value":
                slots[slot] = "value"
            elif value not in dims_list:
                msg = (
                    f"Dimension {value!r} assigned to slot {slot!r} "
                    f"is not in the data dimensions: {dims_list}"
                )
                raise ValueError(msg)
            else:
                slots[slot] = value
                used_dims.add(value)
            if slot in available_slots:
                available_slots.remove(slot)

    # Pass 2: Fill remaining slots with remaining dims (by position)
    remaining_dims = [d for d in dims_list if d not in used_dims]
    for slot, dim in zip(available_slots, remaining_dims, strict=False):
        slots[slot] = dim
        used_dims.add(dim)

    # Check for unassigned dimensions
    unassigned = [d for d in dims_list if d not in used_dims]
    if unassigned and not allow_unassigned:
        msg = (
            f"Unassigned dimension(s): {unassigned}. "
            "Reduce with .sel(), .isel(), or .mean() before plotting."
        )
        raise ValueError(msg)

    return slots