diff --git a/doc/api/next_api_changes/deprecations/27175-AL.rst b/doc/api/next_api_changes/deprecations/27175-AL.rst new file mode 100644 index 000000000000..3fce05765a59 --- /dev/null +++ b/doc/api/next_api_changes/deprecations/27175-AL.rst @@ -0,0 +1,5 @@ +Mixing positional and keyword arguments for ``legend`` handles and labels +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +This previously only raised a warning, but is now formally deprecated. If +passing *handles* and *labels*, they must be passed either both positionally or +both as keyword. diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 58e5dfcfe3b8..c46770974567 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -1301,7 +1301,7 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): legend(handles=handles, labels=labels) The behavior for a mixture of positional and keyword handles and labels - is undefined and issues a warning. + is undefined and issues a warning; it will be an error in the future. Parameters ---------- @@ -1334,8 +1334,10 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): handlers = kwargs.get('handler_map') if (handles is not None or labels is not None) and args: - _api.warn_external("You have mixed positional and keyword arguments, " - "some input may be discarded.") + _api.warn_deprecated("3.9", message=( + "You have mixed positional and keyword arguments, some input may " + "be discarded. This is deprecated since %(since)s and will " + "become an error %(removal)s.")) if (hasattr(handles, "__len__") and hasattr(labels, "__len__") and diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 3a35b4051c71..90b0a3f38999 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -405,10 +405,10 @@ def test_warn_mixed_args_and_kwargs(self): th = np.linspace(0, 2*np.pi, 1024) lns, = ax.plot(th, np.sin(th), label='sin') lnc, = ax.plot(th, np.cos(th), label='cos') - with pytest.warns(UserWarning) as record: + with pytest.warns(DeprecationWarning) as record: ax.legend((lnc, lns), labels=('a', 'b')) assert len(record) == 1 - assert str(record[0].message) == ( + assert str(record[0].message).startswith( "You have mixed positional and keyword arguments, some input may " "be discarded.") @@ -474,10 +474,10 @@ def test_warn_args_kwargs(self): fig, axs = plt.subplots(1, 2) lines = axs[0].plot(range(10)) lines2 = axs[1].plot(np.arange(10) * 2.) - with pytest.warns(UserWarning) as record: + with pytest.warns(DeprecationWarning) as record: fig.legend((lines, lines2), labels=('a', 'b')) assert len(record) == 1 - assert str(record[0].message) == ( + assert str(record[0].message).startswith( "You have mixed positional and keyword arguments, some input may " "be discarded.")