'Alternative formating of units in plot labels

When plotting xarry DataArrays, I would like to select a different formatting of the units in plotting labels, e.g. mass (kg) or mass in kg instead of the default backets units [kg]. If've found a similar comment (https://github.com/pydata/xarray/pull/2151#pullrequestreview-121662163) but no other.

As I see it, it is currently hard-coded in file https://github.com/pydata/xarray/blob/main/xarray/plot/utils.py (see code below)

def _get_units_from_attrs(da):
    """Extracts and formats the unit/units from a attributes."""
    pint_array_type = DuckArrayModule("pint").type
    units = " [{}]"
    if isinstance(da.data, pint_array_type):
        units = units.format(str(da.data.units))
    elif da.attrs.get("units"):
        units = units.format(da.attrs["units"])
    elif da.attrs.get("unit"):
        units = units.format(da.attrs["unit"])
    else:
        units = ""
    return units

Is there a solution for me to change the units formatting style? Thanks!



Solution 1:[1]

In the meantime I found a workaround using a matplotlib projection class:

class XarrayLabelManipulation(plt.Axes):
    def _adjust_units_label(self, label, units_format='in'):
        if label:
            # other formats: '(', '[', '/', 'in'
            if not label[-1] == ']':
                return label
            if units_format== '[':
                return label
            idx0 = label.rfind('[', 1)
            units_string = label[idx0:]
            if units_format== 'in':
                return label.replace(units_string, f' in {units_string[1:-1]}')
            if units_format== '/':
                return label.replace(units_string, f' / {units_string[1:-1]}')
            if units_format== '(in)':
                return label.replace(units_string, f' ({units_string[1:-1]})')

    def set_xlabel(self, xlabel, *args, **kwargs):
        super().set_xlabel(self._adjust_units_label(xlabel), *args, **kwargs)

    def set_ylabel(self, ylabel, *args, **kwargs):
        super().set_ylabel(self._adjust_units_label(ylabel), *args, **kwargs)

proj.register_projection(XarrayLabelManipulation)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1