Skip to content

Commit 4109966

Browse files
tomchorIllviljandcherian
authored
Improves rendering of complex LaTeX expressions as long_names when 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 <[email protected]> * Update xarray/tests/test_utils.py Co-authored-by: Illviljan <[email protected]> * 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 <[email protected]> Co-authored-by: Deepak Cherian <[email protected]>
1 parent 2705c63 commit 4109966

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ v0.19.1 (unreleased)
2222

2323
New Features
2424
~~~~~~~~~~~~
25+
- Xarray now does a better job rendering variable names that are long LaTeX sequences when plotting (:issue:`5681`, :pull:`5682`).
26+
By `Tomas Chor <https://github.com/tomchor>`_.
2527
- Add a option to disable the use of ``bottleneck`` (:pull:`5560`)
2628
By `Justus Magin <https://github.com/keewis>`_.
2729
- Added ``**kwargs`` argument to :py:meth:`open_rasterio` to access overviews (:issue:`3269`).

xarray/plot/utils.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,13 @@ def _get_units_from_attrs(da):
490490
else:
491491
units = _get_units_from_attrs(da)
492492

493-
return "\n".join(textwrap.wrap(name + extra + units, 30))
493+
# Treat `name` differently if it's a latex sequence
494+
if name.startswith("$") and (name.count("$") % 2 == 0):
495+
return "$\n$".join(
496+
textwrap.wrap(name + extra + units, 60, break_long_words=False)
497+
)
498+
else:
499+
return "\n".join(textwrap.wrap(name + extra + units, 30))
494500

495501

496502
def _interval_to_mid_points(array):

xarray/tests/test_plot.py

+7
Original file line numberDiff line numberDiff line change
@@ -2950,3 +2950,10 @@ def test_datarray_scatter(x, y, z, hue, markersize, row, col, add_legend, add_co
29502950
add_legend=add_legend,
29512951
add_colorbar=add_colorbar,
29522952
)
2953+
2954+
2955+
def test_latex_name_isnt_split():
2956+
da = xr.DataArray()
2957+
long_latex_name = r"$Ra_s = \mathrm{mean}(\epsilon_k) / \mu M^2_\infty$"
2958+
da.attrs = dict(long_name=long_latex_name)
2959+
assert label_from_attrs(da) == long_latex_name

0 commit comments

Comments
 (0)