-
-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Description
Bug summary
Passing a non-string value (like a NumPy array) to orientation in Axes.grouped_bar() triggers a misleading “ambiguous truth value” error from _api.check_in_list. The function should instead raise a clear ValueError stating the value is not valid.
Code for reproduction
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.grouped_bar([[1, 2, 3], [3, 2, 1]], orientation=np.array([1, 2, 3]))Actual outcome
Axes.grouped_bar() fails inside _api.check_in_list() because NumPy arrays cannot be evaluated in a boolean context.
Instead of raising a clear validation error, it produces a misleading NumPy truth-value error, causing the test to fail.
Expected outcome
After applying the fix, invalid inputs (including NumPy arrays) are handled gracefully, and all tests expecting a clear ValueError now pass.
Additional information
- Conditions under which this bug happens:
The bug occurs whenever the orientation parameter passed to Axes.grouped_bar() is not a string, such as:
orientation = np.array([1, 2, 3]) # NumPy array
orientation = 1 # integer
orientation = None # NoneType
These types trigger an internal truth-value evaluation inside _api.check_in_list, which expects a scalar comparable value (like a string).
- Edge cases affected:
NumPy arrays (np.array([...]))
Non-string types (integers, floats, None, lists, etc.)
Any custom object that doesn’t implement eq safely with strings
- Behavior in earlier versions:
This issue has likely existed since the introduction of Axes.grouped_bar() (Matplotlib 3.11, provisional API).
Other similar Matplotlib APIs (e.g., barh, stem, etc.) already validate string-type enums, so they are not affected.
- Root cause (why this happens):
The function directly calls:
_api.check_in_list(["vertical", "horizontal"], orientation=orientation)
When orientation is a NumPy array, the expression val not in values inside check_in_list() performs elementwise comparison, returning an array of booleans.
Python then attempts to interpret that array as a single truth value, which triggers NumPy’s error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
- Proposed fix (confirmed working):
Add an early type guard before calling _api.check_in_list():
if not isinstance(orientation, str):
raise ValueError(f"{orientation!r} is not a valid value for orientation")
_api.check_in_list(["vertical", "horizontal"], orientation=orientation)
-- This ensures non-string inputs are rejected immediately and consistently,
-- prevents the ambiguous truth-value error, and
-- aligns grouped_bar() with Matplotlib’s standard API validation behavior.
Operating system
MacOS
Matplotlib Version
3.11.0.dev1446+g319295e28.d20251030
Matplotlib Backend
macosx
Python version
Python 3.13.7
Jupyter version
No response
Installation
pip