Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[MNT]: handle new deprecation from numpy (casting single-element arrays to scalar) #25744

Closed as not planned
@neutrinoceros

Description

@neutrinoceros

Summary

For context, see numpy/numpy#10615

One way matplotlib currently hits the new deprecation warning (there might be others) can be reproduced as

# t.py
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_ylim(np.array([-1]), 1)
$ python -Werror t.py
Traceback (most recent call last):
  File "/Users/robcleme/dev/matplotlib/t.py", line 6, in <module>
    ax.set_ylim(np.array([-1]), 1)
  File "/Users/robcleme/dev/matplotlib/lib/matplotlib/axes/_base.py", line 3873, in set_ylim
    return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/robcleme/dev/matplotlib/lib/matplotlib/axis.py", line 1214, in _set_lim
    v0, v1 = self.get_major_locator().nonsingular(v0, v1)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/robcleme/dev/matplotlib/lib/matplotlib/ticker.py", line 1644, in nonsingular
    return mtransforms.nonsingular(v0, v1, expander=.05)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/robcleme/dev/matplotlib/lib/matplotlib/transforms.py", line 2844, in nonsingular
    vmin, vmax = map(float, [vmin, vmax])
    ^^^^^^^^^^
DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.)

Proposed fix

The following patch resolves the one issue for which I included a reproducer

diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py
index 03c8a9f97a..aa345fb295 100644
--- a/lib/matplotlib/transforms.py
+++ b/lib/matplotlib/transforms.py
@@ -2841,7 +2841,7 @@ def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):

     # Expand vmin, vmax to float: if they were integer types, they can wrap
     # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
-    vmin, vmax = map(float, [vmin, vmax])
+    vmin, vmax = map(lambda x: float(np.asarray(x).item()), [vmin, vmax])

     maxabsvalue = max(abs(vmin), abs(vmax))
     if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:

I will open a PR with this patch, but careful inspection is needed to make sure the rest of the code base is safe.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions