Skip to content

Commit 782e0e2

Browse files
authored
Use divergent colormap if lowest and highest level span 0 (#3913)
* Use divergent colormap if lowest and highest level span 0 Fixes #3524 * sort levels by default. * better levels check
1 parent 8d280cd commit 782e0e2

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ Bug fixes
5757
- Fix a regression where deleting a coordinate from a copied :py:class:`DataArray`
5858
can affect the original :py:class:`Dataarray`. (:issue:`3899`, :pull:`3871`)
5959
By `Todd Jennings <https://github.com/toddrjen>`_
60+
- Use divergent colormap if ``levels`` spans 0. (:issue:`3524`)
61+
By `Deepak Cherian <https://github.com/dcherian>`_
6062
- Fix ``FacetGrid`` when ``vmin == vmax``. (:issue:`3734`)
6163
By `Deepak Cherian <https://github.com/dcherian>`_
6264
- Fix bug where plotting line plots with 2D coordinates depended on dimension

xarray/plot/utils.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ def _determine_cmap_params(
169169
"""
170170
import matplotlib as mpl
171171

172+
if isinstance(levels, Iterable):
173+
levels = sorted(levels)
174+
172175
calc_data = np.ravel(plot_data[np.isfinite(plot_data)])
173176

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

218221
if possibly_divergent:
222+
levels_are_divergent = (
223+
isinstance(levels, Iterable) and levels[0] * levels[-1] < 0
224+
)
219225
# kwargs not specific about divergent or not: infer defaults from data
220-
divergent = ((vmin < 0) and (vmax > 0)) or not center_is_none
226+
divergent = (
227+
((vmin < 0) and (vmax > 0)) or not center_is_none or levels_are_divergent
228+
)
221229
else:
222230
divergent = False
223231

xarray/tests/test_plot.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,12 @@ def test_divergentcontrol(self):
844844
assert cmap_params["vmax"] == 0.6
845845
assert cmap_params["cmap"] == "viridis"
846846

847+
# regression test for GH3524
848+
# infer diverging colormap from divergent levels
849+
cmap_params = _determine_cmap_params(pos, levels=[-0.1, 0, 1])
850+
# specifying levels makes cmap a Colormap object
851+
assert cmap_params["cmap"].name == "RdBu_r"
852+
847853
def test_norm_sets_vmin_vmax(self):
848854
vmin = self.data.min()
849855
vmax = self.data.max()

0 commit comments

Comments
 (0)