Skip to content

Commit ede8e56

Browse files
authored
Merge pull request matplotlib#17546 from rlung/legend_elements
`func` argument in `legend_elements` with non-monotonically increasing functions
2 parents 4f02c73 + 986debe commit ede8e56

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/matplotlib/collections.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,8 +1076,10 @@ def legend_elements(self, prop="colors", num="auto",
10761076
cond = ((label_values >= func(arr).min()) &
10771077
(label_values <= func(arr).max()))
10781078
label_values = label_values[cond]
1079-
xarr = np.linspace(arr.min(), arr.max(), 256)
1080-
values = np.interp(label_values, func(xarr), xarr)
1079+
yarr = np.linspace(arr.min(), arr.max(), 256)
1080+
xarr = func(yarr)
1081+
ix = np.argsort(xarr)
1082+
values = np.interp(label_values, xarr[ix], yarr[ix])
10811083

10821084
kw = dict(markeredgewidth=self.get_linewidths()[0],
10831085
alpha=self.get_alpha())

lib/matplotlib/tests/test_collections.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,3 +660,30 @@ def test_quadmesh_set_array():
660660
coll.set_array(np.ones(9))
661661
fig.canvas.draw()
662662
assert np.array_equal(coll.get_array(), np.ones(9))
663+
664+
665+
def test_legend_inverse_size_label_relationship():
666+
"""
667+
Ensure legend markers scale appropriately when label and size are
668+
inversely related.
669+
Here label = 5 / size
670+
"""
671+
672+
np.random.seed(19680801)
673+
X = np.random.random(50)
674+
Y = np.random.random(50)
675+
C = 1 - np.random.random(50)
676+
S = 5 / C
677+
678+
legend_sizes = [0.2, 0.4, 0.6, 0.8]
679+
fig, ax = plt.subplots()
680+
sc = ax.scatter(X, Y, s=S)
681+
handles, labels = sc.legend_elements(
682+
prop='sizes', num=legend_sizes, func=lambda s: 5 / s
683+
)
684+
685+
# Convert markersize scale to 's' scale
686+
handle_sizes = [x.get_markersize() for x in handles]
687+
handle_sizes = [5 / x**2 for x in handle_sizes]
688+
689+
assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1)

0 commit comments

Comments
 (0)