Skip to content

Feature/dataset notebook#11

Merged
FBumann merged 4 commits intomainfrom
feature/dataset-notebook
Jan 9, 2026
Merged

Feature/dataset notebook#11
FBumann merged 4 commits intomainfrom
feature/dataset-notebook

Conversation

@FBumann
Copy link
Owner

@FBumann FBumann commented Jan 9, 2026

Summary by CodeRabbit

  • Documentation

    • Added an example notebook demonstrating end-to-end dataset plotting with multiple variables, placement controls, config examples, varied plot types, and a new Examples nav entry.
  • New Features

    • Introduced a configurable option to control where the dataset "variable" dimension is placed across plot slots.
    • Plotting now supports selecting a single variable or plotting all variables with automatic and explicit slot assignment.

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

@coderabbitai
Copy link

coderabbitai bot commented Jan 9, 2026

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Adds a new example notebook demonstrating end-to-end dataset plotting with xarray_plotly and introduces a new configuration option dataset_variable_position to control placement of the derived "variable" dimension when plotting all variables. The Dataset accessor gains optional var: str | None parameters and reorders the "variable" dimension per the new option.

Changes

Cohort / File(s) Summary
Documentation & Navigation
docs/examples/datasets.ipynb, mkdocs.yml
New example notebook showing multi-variable dataset plotting, slot placement patterns, and multiple plot types; navigation entry added to mkdocs.yml.
Configuration System
xarray_plotly/config.py
Added public option dataset_variable_position: int = 1 to Options; set_options() accepts dataset_variable_position; option included in Options.to_dict() and context restore logic.
Data Accessor & Public API
xarray_plotly/accessor.py
DatasetPlotlyAccessor._get_dataarray() updated to reorder the constructed "variable" dimension using _options.dataset_variable_position for all-variable plots; plotting methods (line, bar, area, scatter, box, pie) now accept `var: str

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Add pie plots #8 — Related changes to DatasetPlotlyAccessor's pie method and use of _get_dataarray with var: str | None.
  • Add dataset plotting accessor #2 — Earlier work on DatasetPlotlyAccessor._get_dataarray() and multi-variable DataArray construction that this PR extends.

Poem

🐰 I nibbled code beneath the moonlit sky,

Variables hopped and learned to multiply,
I nudged their places—left, right, near, or far,
Now plots align like carrots in a jar,
Hop, plot, repeat — a rabbit's coding star ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Feature/dataset notebook' is vague and uses non-descriptive terminology that doesn't convey meaningful information about the changeset. While it generically references 'dataset notebook', it fails to clarify the actual feature being added. Consider a more descriptive title like 'Add dataset plotting example notebook' or 'Add xarray dataset visualization notebook' that clearly indicates what feature is being introduced.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% 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

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7beece7 and ad61ad2.

📒 Files selected for processing (2)
  • docs/examples/datasets.ipynb
  • xarray_plotly/accessor.py

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

🤖 Fix all issues with AI agents
In @docs/examples/datasets.ipynb:
- Around line 112-116: The current note incorrectly states "Dimensions are:
(time, variable, city)" while ds.to_array().dims actually returns
('variable','time','city') because to_array() puts the new variable dimension
first; update the explanatory text (or remove the ds.to_array() print) to
clarify that the printed dims reflect to_array() behavior and that the dimension
reordering that moves "variable" to position 1 happens only when plotting via
the xpx(...).line accessor; reference ds.to_array() for the print and
xpx(ds).line for the plotting behavior so readers understand when each reorder
occurs.

In @xarray_plotly/accessor.py:
- Around line 363-371: The negative index handling for dataset_variable_position
is incorrect; replace the current "any negative => append" logic by computing a
proper insertion index using Python-style negative indexing: after building dims
= list(da.dims) and removing "variable", compute insert_idx = pos if pos >= 0
else len(dims) + pos + 1, then validate that 0 <= insert_idx <= len(dims) (raise
ValueError for out-of-range pos), and finally do dims.insert(insert_idx,
"variable") before da = da.transpose(*dims); reference symbols: da, dims, pos,
dataset_variable_position.
🧹 Nitpick comments (2)
xarray_plotly/config.py (1)

114-126: Consider adding input validation for dataset_variable_position.

While the implementation correctly propagates the configuration value, there's no validation to ensure the position is within reasonable bounds. Consider adding validation to provide clear error messages if users provide invalid values.

♻️ Optional validation enhancement
 @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.
+    
+    Raises:
+        ValueError: If dataset_variable_position is invalid.

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

+    # Validate dataset_variable_position
+    if dataset_variable_position is not None:
+        if not isinstance(dataset_variable_position, int):
+            raise TypeError(f"dataset_variable_position must be an int, got {type(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
xarray_plotly/accessor.py (1)

358-358: Consider moving import to module level.

The import of _options is inside the method, which incurs a small overhead on every call. Since this is internal API usage within the same package, consider importing at the module level.

♻️ Refactor: Move to module-level import
 """Accessor classes for Plotly Express plotting on DataArray and Dataset."""

 from typing import Any, ClassVar

 import plotly.graph_objects as go
 from xarray import DataArray, Dataset

 from xarray_plotly import plotting
 from xarray_plotly.common import SlotValue, auto
+from xarray_plotly.config import _options

Then update line 358:

         if var is None:
-            from xarray_plotly.config import _options
-
             da = self._ds.to_array(dim="variable")
             pos = _options.dataset_variable_position
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 473c12c and 7beece7.

📒 Files selected for processing (4)
  • docs/examples/datasets.ipynb
  • mkdocs.yml
  • xarray_plotly/accessor.py
  • xarray_plotly/config.py
🔇 Additional comments (4)
mkdocs.yml (1)

72-72: LGTM!

The navigation entry for the new dataset plotting example is correctly formatted and properly positioned within the Examples section.

xarray_plotly/config.py (1)

61-73: LGTM! Clear documentation and sensible default.

The new dataset_variable_position option is well-documented and follows the established pattern for configuration options. The default value of 1 (second position, typically color) is a sensible choice for most use cases.

xarray_plotly/accessor.py (1)

352-356: LGTM! Clear documentation of the positioning behavior.

The updated docstring clearly explains that the "variable" dimension is positioned according to the configuration option, with appropriate defaults mentioned.

docs/examples/datasets.ipynb (1)

1-260: Excellent comprehensive documentation!

The notebook provides clear, well-structured examples demonstrating:

  • Basic dataset plotting with automatic variable dimension handling
  • Explicit slot assignments for the "variable" dimension
  • Configuration of default positioning behavior
  • Multiple plot types (line, bar, box, area, scatter, pie)
  • Mixing explicit and automatic slot assignments

This will be very helpful for users learning to work with multi-variable datasets.

  1. Notebook comment - Clarified that to_array() returns (variable, ...) but xpx() reorders it
  2. Negative indexing - Now supports Python-style: -1=last, -2=second-to-last, etc.
  3. Import - Moved _options to module level
@FBumann FBumann merged commit 3739f28 into main Jan 9, 2026
5 of 6 checks passed
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