Skip to content

Add dataset plotting accessor#2

Merged
FBumann merged 1 commit intomainfrom
feature/dataset-plotting
Jan 9, 2026
Merged

Add dataset plotting accessor#2
FBumann merged 1 commit intomainfrom
feature/dataset-plotting

Conversation

@FBumann
Copy link
Owner

@FBumann FBumann commented Jan 9, 2026

Summary by CodeRabbit

  • New Features

    • Dataset-level plotting now supported alongside individual data array plotting.
    • Enhanced plot function to handle both data arrays and datasets.
    • Multi-variable visualization with all chart types (line, bar, area, scatter, box).
  • Tests

    • Added comprehensive test coverage for new dataset plotting functionality.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 9, 2026

📝 Walkthrough

Walkthrough

Dataset-level plotting support is added to xarray_plotly through a new DatasetPlotlyAccessor class. The xpx() function is updated to accept either DataArray or Dataset inputs and dispatch to the corresponding accessor type using overload typing. Comprehensive test coverage validates both accessor implementations.

Changes

Cohort / File(s) Summary
Accessor Implementation
xarray_plotly/accessor.py
Added DatasetPlotlyAccessor class with line, bar, area, scatter, and box plotting methods. Each method accepts optional var parameter to select single or all variables, delegates to existing plotting utilities, and supports consistent parameter semantics (x, color, facet_col/row, animation_frame, etc.). Internal _get_dataarray() helper converts dataset variables to DataArray with "variable" dimension when needed.
Public API & Type Dispatch
xarray_plotly/__init__.py
Updated xpx() function with @overload type hints to differentiate DataArray vs Dataset inputs. Extended imports to include Dataset and register_dataset_accessor. Registered DatasetPlotlyAccessor as dataset accessor. Added DatasetPlotlyAccessor to \_\all\_\ exports. Module docstring updated to reference Dataset support.
Test Coverage
tests/test_accessor.py
Added tests verifying xpx() behavior with DataArray (returns accessor with imshow) and Dataset (returns accessor without imshow). Introduced TestDatasetPlotlyAccessor class validating line, bar, area, scatter, and box plot methods on Dataset.plotly accessor. Added equivalence tests comparing xpx() output with direct accessor usage.

Sequence Diagram

sequenceDiagram
    participant User
    participant xpx as xpx() Function
    participant DAcc as DataArrayPlotlyAccessor
    participant DSAcc as DatasetPlotlyAccessor
    participant Plotting as Plotting Utilities
    
    User->>xpx: xpx(dataarray)
    xpx->>DAcc: Create accessor
    DAcc-->>User: Return accessor
    User->>DAcc: .line()
    DAcc->>Plotting: delegate to plotting.line()
    Plotting-->>DAcc: Return Figure
    DAcc-->>User: Return Figure
    
    User->>xpx: xpx(dataset)
    xpx->>DSAcc: Create accessor
    DSAcc-->>User: Return accessor
    User->>DSAcc: .line(var=None)
    DSAcc->>DSAcc: _get_dataarray() converts to DataArray
    DSAcc->>Plotting: delegate to plotting.line()
    Plotting-->>DSAcc: Return Figure
    DSAcc-->>User: Return Figure
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hoppy Bits of Code

With datasets now plotting with glee,
Two accessors dance wild and free,
The xpx dispatcher knows the way,
From DataArray to Dataset play,
Our plotting meadow grows today! 🌱📊

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Add dataset plotting accessor' accurately describes the main change: introducing a new DatasetPlotlyAccessor class for dataset-level plotting capabilities alongside the existing DataArrayPlotlyAccessor.
Docstring Coverage ✅ Passed Docstring coverage is 88.46% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/test_accessor.py (2)

37-61: Tests verify type but not actual equivalence.

The test names suggest verifying equivalence between xpx(da).line() and da.plotly.line(), but only the return type is checked. Consider adding assertions that compare trace counts or data to ensure both paths produce identical figures.

💡 Optional enhancement
     def test_xpx_dataarray_equivalent_to_accessor(self) -> None:
         """Test that xpx(da).line() works the same as da.plotly.line()."""
         da = xr.DataArray(
             np.random.rand(10, 3),
             dims=["time", "city"],
             coords={"time": np.arange(10), "city": ["A", "B", "C"]},
             name="test",
         )
         fig1 = xpx(da).line()
         fig2 = da.plotly.line()
         assert isinstance(fig1, go.Figure)
         assert isinstance(fig2, go.Figure)
+        assert len(fig1.data) == len(fig2.data)

235-294: Good test coverage for DatasetPlotlyAccessor.

The test class validates accessor availability and basic plotting functionality. Consider adding a test for error handling when an invalid variable name is passed to var.

💡 Optional: Add error handling test
def test_line_invalid_variable_raises(self) -> None:
    """Test that invalid variable name raises KeyError."""
    with pytest.raises(KeyError):
        self.ds.plotly.line(var="nonexistent")
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 23ce8ff and ec7959d.

📒 Files selected for processing (3)
  • tests/test_accessor.py
  • xarray_plotly/__init__.py
  • xarray_plotly/accessor.py
🧰 Additional context used
🧬 Code graph analysis (1)
xarray_plotly/__init__.py (1)
xarray_plotly/accessor.py (1)
  • DatasetPlotlyAccessor (278-521)
🔇 Additional comments (9)
tests/test_accessor.py (1)

18-35: LGTM! Good coverage for xpx function dispatch.

The tests correctly verify that xpx() returns the appropriate accessor type based on input (DataArray vs Dataset) and validates the expected method availability, including the intentional absence of imshow on the Dataset accessor.

xarray_plotly/__init__.py (3)

67-72: LGTM! Well-structured overloads for type-safe dispatch.

The overload definitions correctly specify the return types for DataArray and Dataset inputs, enabling proper IDE code completion and type checking.


75-101: LGTM! Clean implementation with correct dispatch order.

The implementation correctly checks for Dataset first before falling back to DataArrayPlotlyAccessor. The type hints and overloads provide adequate guidance to users.


106-108: LGTM! Accessor registration follows xarray conventions.

Both DataArray and Dataset accessors are correctly registered under the same "plotly" namespace, providing a consistent API surface.

xarray_plotly/accessor.py (5)

278-317: LGTM! Well-documented class with clear examples.

The class docstring clearly explains the variable plotting behavior and provides useful examples showing both all-variable and single-variable plotting patterns.


319-323: LGTM! Simple and effective helper method.

The method correctly handles both cases: converting the entire Dataset to a DataArray with a "variable" dimension, or selecting a single variable. Invalid variable names will naturally raise a KeyError from xarray, which is appropriate behavior.


325-365: LGTM! Consistent API with DataArrayPlotlyAccessor.

The method signature mirrors the DataArray version with the addition of var as a positional parameter, enabling clean usage patterns like ds.plotly.line("temp").


367-521: LGTM! All plotting methods follow consistent patterns.

The bar, area, scatter, and box methods correctly mirror their DataArray counterparts with consistent parameter signatures and defaults. The delegation to the shared plotting module ensures consistent behavior.


310-310: LGTM! Correct method exposure.

The __all__ list appropriately excludes imshow, which makes sense since Dataset.to_array() produces a higher-dimensional array that isn't suitable for heatmap visualization without additional dimension handling.

@FBumann FBumann merged commit 8519bc8 into main Jan 9, 2026
5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 9, 2026
@FBumann FBumann deleted the feature/dataset-plotting branch January 9, 2026 14:03
@coderabbitai coderabbitai bot mentioned this pull request Jan 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant