diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 9ac9639b8c1..52114be991b 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -22,6 +22,8 @@ v0.19.1 (unreleased) New Features ~~~~~~~~~~~~ +- Xarray now does a better job rendering variable names that are long LaTeX sequences when plotting (:issue:`5681`, :pull:`5682`). + By `Tomas Chor `_. - Add a option to disable the use of ``bottleneck`` (:pull:`5560`) By `Justus Magin `_. - Added ``**kwargs`` argument to :py:meth:`open_rasterio` to access overviews (:issue:`3269`). diff --git a/xarray/plot/utils.py b/xarray/plot/utils.py index f2f296096a5..af5859c1f14 100644 --- a/xarray/plot/utils.py +++ b/xarray/plot/utils.py @@ -490,7 +490,13 @@ def _get_units_from_attrs(da): else: units = _get_units_from_attrs(da) - return "\n".join(textwrap.wrap(name + extra + units, 30)) + # Treat `name` differently if it's a latex sequence + if name.startswith("$") and (name.count("$") % 2 == 0): + return "$\n$".join( + textwrap.wrap(name + extra + units, 60, break_long_words=False) + ) + else: + return "\n".join(textwrap.wrap(name + extra + units, 30)) def _interval_to_mid_points(array): diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index ee8bafb8fa7..e358bd47485 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -2950,3 +2950,10 @@ def test_datarray_scatter(x, y, z, hue, markersize, row, col, add_legend, add_co add_legend=add_legend, add_colorbar=add_colorbar, ) + + +def test_latex_name_isnt_split(): + da = xr.DataArray() + long_latex_name = r"$Ra_s = \mathrm{mean}(\epsilon_k) / \mu M^2_\infty$" + da.attrs = dict(long_name=long_latex_name) + assert label_from_attrs(da) == long_latex_name