FIX: make unpack a true fallback by jklymak · Pull Request #31165 · matplotlib/matplotlib
I tested that this works fine with pint if pint is setup properly:
def test_pint_plot():
"""Test that pint Quantity objects work in matplotlib plots."""
try:
import pint
import matplotlib.pyplot as plt
except ImportError:
print("⊘ pint plot test skipped (pint not installed)")
return
ureg = pint.UnitRegistry()
ureg.setup_matplotlib()
# Check if pint has a registered converter
from matplotlib import units as munits
pint_quantity_type = type(1.0 * ureg.meter)
has_converter = pint_quantity_type in munits.registry
print(f" → Pint has registered converter: {has_converter}")
# Try plotting with pint quantities
x = np.array([0, 1, 2, 3, 4]) * ureg.second
y = np.array([0, 1, 4, 9, 16]) * ureg.meter
y2 = np.array([0, 10, 40, 90, 160]) * ureg.centimeter
try:
fig, ax = plt.subplots()
ax.plot(x, y, 'o-')
ax.plot(x, y2, 's-')
ax.set_xlabel('Time')
ax.set_ylabel('Distance')
ax.set_title('Plot with Pint Quantities')
fig.savefig('test_pint_plot.png')
print("✓ pint plot test passed (saved to test_pint_plot.png)")
except Exception as e:
print(f"✗ pint plot test failed: {e}")
Note that if you do not call ureg.setup_matplotlib() then you get warnings and the plot does not have the correct units:
Users/jklymak/matplotlib/lib/matplotlib/cbook.py:2451: UnitStrippedWarning: The unit of the quantity is stripped when downcasting to ndarray.
xtmp = np.asarray(x)
/Users/jklymak/matplotlib/lib/matplotlib/cbook.py:1373: UnitStrippedWarning: The unit of the quantity is stripped when downcasting to ndarray.
so the fallback works with pint.
It also works fine with xarray and pandas.
x_data = np.array([0, 1, 2, 3, 4])
y_data = np.array([0, 1, 4, 9, 16])
x = pd.Series(x_data)
y = pd.Series(y_data)
try:
fig, ax = plt.subplots()
ax.plot(x, y, 'o-')
ax.set_xlabel('X (Series)')