Skip to content

Commit

Permalink
Improves rendering of complex LaTeX expressions as long_names when …
Browse files Browse the repository at this point in the history
…plotting (#5682)

* try to wrap texts differently if they're latex code

* added space around modulo operator

* prevents breaking up of long words

* added test for label_from_attrs() function with a long latex string

* Update xarray/plot/utils.py

Co-authored-by: Illviljan <14371165+Illviljan@users.noreply.github.com>

* Update xarray/tests/test_utils.py

Co-authored-by: Illviljan <14371165+Illviljan@users.noreply.github.com>

* moved test_latex_name_isnt_split() to test_plots

* Apply suggestions from code review

* fixed test_latex_name_isnt_split()

* ran code through pre-commit

* updated whats-new.rst

Co-authored-by: Illviljan <14371165+Illviljan@users.noreply.github.com>
Co-authored-by: Deepak Cherian <dcherian@users.noreply.github.com>
  • Loading branch information
3 people authored Aug 17, 2021
1 parent 2705c63 commit 4109966
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/tomchor>`_.
- Add a option to disable the use of ``bottleneck`` (:pull:`5560`)
By `Justus Magin <https://github.com/keewis>`_.
- Added ``**kwargs`` argument to :py:meth:`open_rasterio` to access overviews (:issue:`3269`).
Expand Down
8 changes: 7 additions & 1 deletion xarray/plot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 4109966

Please sign in to comment.