Skip to content

Commit

Permalink
Use divergent colormap if lowest and highest level span 0 (pydata#3913)
Browse files Browse the repository at this point in the history
* Use divergent colormap if lowest and highest level span 0

Fixes pydata#3524

* sort levels by default.

* better levels check
  • Loading branch information
dcherian authored Apr 5, 2020
1 parent 8d280cd commit 782e0e2
Show file tree
Hide file tree
Showing 3 changed files with 17 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 @@ -57,6 +57,8 @@ Bug fixes
- Fix a regression where deleting a coordinate from a copied :py:class:`DataArray`
can affect the original :py:class:`Dataarray`. (:issue:`3899`, :pull:`3871`)
By `Todd Jennings <https://github.com/toddrjen>`_
- Use divergent colormap if ``levels`` spans 0. (:issue:`3524`)
By `Deepak Cherian <https://github.com/dcherian>`_
- Fix ``FacetGrid`` when ``vmin == vmax``. (:issue:`3734`)
By `Deepak Cherian <https://github.com/dcherian>`_
- Fix bug where plotting line plots with 2D coordinates depended on dimension
Expand Down
10 changes: 9 additions & 1 deletion xarray/plot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,9 @@ def _determine_cmap_params(
"""
import matplotlib as mpl

if isinstance(levels, Iterable):
levels = sorted(levels)

calc_data = np.ravel(plot_data[np.isfinite(plot_data)])

# Handle all-NaN input data gracefully
Expand Down Expand Up @@ -216,8 +219,13 @@ def _determine_cmap_params(
vlim = abs(vmax - center)

if possibly_divergent:
levels_are_divergent = (
isinstance(levels, Iterable) and levels[0] * levels[-1] < 0
)
# kwargs not specific about divergent or not: infer defaults from data
divergent = ((vmin < 0) and (vmax > 0)) or not center_is_none
divergent = (
((vmin < 0) and (vmax > 0)) or not center_is_none or levels_are_divergent
)
else:
divergent = False

Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,12 @@ def test_divergentcontrol(self):
assert cmap_params["vmax"] == 0.6
assert cmap_params["cmap"] == "viridis"

# regression test for GH3524
# infer diverging colormap from divergent levels
cmap_params = _determine_cmap_params(pos, levels=[-0.1, 0, 1])
# specifying levels makes cmap a Colormap object
assert cmap_params["cmap"].name == "RdBu_r"

def test_norm_sets_vmin_vmax(self):
vmin = self.data.min()
vmax = self.data.max()
Expand Down

0 comments on commit 782e0e2

Please sign in to comment.