Repository: pydata/xarray

Issue:
FacetGrid plots drop units for
### What happened?

When plotting multiple subplots, using FacetGrid, the units information is dropped from the axis labelling. 

Instead of `x [x_unit]` it now only says `x`.

<img width="728" alt="Image" src="https://github.com/user-attachments/assets/e865dd9e-27e0-42bf-8e98-da1c0c8a0509" />

### What did you expect to happen?

Instead, the labels should correctly include the specified xarray units.

<img width="728" alt="Image" src="https://github.com/user-attachments/assets/3fa97d5e-6f55-47a0-9d5a-9247115108ec" />

### Minimal Complete Verifiable Example

```Python

```

### MVCE confirmation

- [x] Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- [x] Complete example — the example is self-contained, including all data and the text of any traceback.
- [x] Verifiable example — the example copy & pastes into an IPython prompt or [Binder notebook](https://mybinder.org/v2/gh/pydata/xarray/main?urlpath=lab/tree/doc/examples/blank_template.ipynb), returning the result.
- [x] New issue — a search of GitHub Issues suggests this is not a duplicate.
- [x] Recent environment — the issue occurs with the latest version of xarray and its dependencies.

### Relevant log output

```Python

```

### Anything else we need to know?

_No response_

### Environment

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.11.11 (main, Dec  3 2024, 17:20:40) [Clang 16.0.0 (clang-1600.0.26.4)]
python-bits: 64
OS: Darwin
OS-release: 23.6.0
machine: arm64
processor: arm
byteorder: little
LC_ALL: None
LANG: None
LOCALE: (None, 'UTF-8')
libhdf5: 1.14.6
libnetcdf: None

xarray: 2025.3.0
pandas: 2.2.3
numpy: 2.1.3
scipy: 1.15.2
netCDF4: None
pydap: None
h5netcdf: None
h5py: 3.13.0
zarr: None
cftime: None
nc_time_axis: None
iris: None
bottleneck: None
dask: None
distributed: None
matplotlib: 3.10.1
cartopy: None
seaborn: None
numbagg: None
fsspec: None
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: 78.1.0
pip: None
conda: None
pytest: 8.3.5
mypy: None
IPython: 9.0.2
sphinx: None
</details>



Discussion:
Thanks for opening your first issue here at xarray! Be sure to follow the issue template!
If you have an idea for a solution, we would really welcome a Pull Request with proposed changes.
See the [Contributing Guide](https://docs.xarray.dev/en/latest/contributing.html) for more.
It may take us a while to respond here, but we really value your contribution. Contributors like you help make xarray better.
Thank you!




Patch:
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index 86c2106a796..b09e797c55a 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -47,7 +47,8 @@ Bug fixes
   By `Mathias Hauser <https://github.com/mathause>`_.
 - Fix grouped and resampled ``first``, ``last`` with datetimes (:issue:`10169`, :pull:`10173`)
   By `Deepak Cherian <https://github.com/dcherian>`_.
-
+- FacetGrid plots now include units in their axis labels when available (:issue:`10184`, :pull:`10185`)
+  By `Andre Wendlinger <https://github.com/andrewendlinger>`_.
 
 Documentation
 ~~~~~~~~~~~~~
diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py
index 82105d5fb6a..2c50c5e1176 100644
--- a/xarray/plot/facetgrid.py
+++ b/xarray/plot/facetgrid.py
@@ -353,6 +353,8 @@ def map_dataarray(
             if k not in {"cmap", "colors", "cbar_kwargs", "levels"}
         }
         func_kwargs.update(cmap_params)
+        # to avoid redundant calling, colorbar and labelling is instead handled
+        # by `_finalize_grid` at the end
         func_kwargs["add_colorbar"] = False
         if func.__name__ != "surface":
             func_kwargs["add_labels"] = False
@@ -375,7 +377,10 @@ def map_dataarray(
                 )
                 self._mappables.append(mappable)
 
-        self._finalize_grid(x, y)
+        xlabel = label_from_attrs(self.data[x])
+        ylabel = label_from_attrs(self.data[y])
+
+        self._finalize_grid(xlabel, ylabel)
 
         if kwargs.get("add_colorbar", True):
             self.add_colorbar(**cbar_kwargs)


Test patch:
diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py
index b9adda5b52d..bfa87386dbc 100644
--- a/xarray/tests/test_plot.py
+++ b/xarray/tests/test_plot.py
@@ -2429,6 +2429,26 @@ def test_facetgrid_polar(self) -> None:
             col="z", subplot_kws=dict(projection="polar"), sharex=False, sharey=False
         )
 
+    @pytest.mark.slow
+    def test_units_appear_somewhere(self) -> None:
+        # assign coordinates to all dims so we can test for units
+        darray = self.darray.assign_coords(
+            {"x": np.arange(self.darray.x.size), "y": np.arange(self.darray.y.size)}
+        )
+
+        darray.x.attrs["units"] = "x_unit"
+        darray.y.attrs["units"] = "y_unit"
+
+        g = xplt.FacetGrid(darray, col="z")
+
+        g.map_dataarray(xplt.contourf, "x", "y")
+
+        alltxt = text_in_fig()
+
+        # unit should appear as e.g. 'x [x_unit]'
+        for unit_name in ["x_unit", "y_unit"]:
+            assert unit_name in "".join(alltxt)
+
 
 @pytest.mark.filterwarnings("ignore:tight_layout cannot")
 class TestFacetGrid4d(PlotTestCase):