Repository navigation
Closed
Closed
Copy link
Milestone
Description
Bug summary
I expected ax.hist([sequence of timedeltas]) to Just Work, as it does with ax.hist([sequence of timestamps]). However, there is a comparison with np.inf that works when the sequence is of timestamps and fails when the sequence is of timedeltas; numpy cannot promote a TimeDelta64DType to a float: https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/axes/_axes.py#L7479
Code for reproduction
import matplotlib.pyplot as plt
import pandas as pd
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(1, 1, 1)
ax.hist(pd.date_range("2026-01-01", "2026-01-05", freq="D"))
ax.hist(pd.date_range("2026-01-01", "2026-01-05", freq="D").diff(1))Actual outcome
numpy.exceptions.DTypePromotionError: The DType <class 'numpy.dtypes.TimeDelta64DType'> could not be promoted by <class 'numpy.dtypes._PyFloatDType'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (<class 'numpy.dtypes.TimeDelta64DType'>, <class 'numpy.dtypes._PyFloatDType'>)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
ax.hist(pd.date_range("2026-01-01", "2026-01-05", freq="D").diff(1))
~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/kylepenner/Documents/numpy/lib/python3.13/site-packages/matplotlib/_api/deprecation.py", line 477, in wrapper
return func(*args, **kwargs)
File "/Users/kylepenner/Documents/numpy/lib/python3.13/site-packages/matplotlib/__init__.py", line 1497, in inner
return func(
ax,
*map(cbook.sanitize_sequence, args),
**{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
File "/Users/kylepenner/Documents/numpy/lib/python3.13/site-packages/matplotlib/axes/_axes.py", line 7479, in hist
xmin = min(xmin, np.nanmin(xi))
numpy._core._exceptions._UFuncNoLoopError: ufunc 'less' did not contain a loop with signature matching types (<class 'numpy.dtypes.TimeDelta64DType'>, <class 'numpy.dtypes._PyFloatDType'>) -> None
Expected outcome
There's an easy way around this---convert the timedeltas to floats with .total_seconds()---but I do prefer the hist call to just work.
Additional information
No response
Operating system
No response
Matplotlib Version
3.11.0.dev1799+g6dbc0c7cd
Matplotlib Backend
No response
Python version
No response
Jupyter version
No response
Installation
git checkout
Activity
jayaprajapatii commentedon Feb 21, 2026
Hii
I reproduce this issue on current main.
Environment:
The failure occurs during histogram range computation in
Axes.hist, wherexmin = np.infandxmax = -np.infare initialized and later compared againstnumpy.timedelta64. After_process_unit_infoandconvert_xunits, the data still containstimedelta64, so the min/max logic involvingnp.inftriggers theDTypePromotionError.I'm looking into adjusting the range computataion to avoid comparisons with
np.inffor non-numeric dtypes.joddeepesh-cloud commentedon Feb 22, 2026
Hi, I also reproduced this on main (Python 3.11, macOS).
It looks like the failure originates from comparisons with np.inf during range computation when the dtype remains timedelta64.
@JayAPrajapati Are you actively working on a fix? If not, I’d be happy to investigate further and propose one.
jayaprajapatii commentedon Feb 22, 2026
@joddeepesh-cloud Yes , I'm actively working on a fix and looking into improving the range computation for non-numeric dtypes like
timedelta64. I'll update with a proposed fix.kdpenner commentedon Feb 22, 2026
to give you an expectation for your solution from the user side: the
ax.hist(pd.date_range("2026-01-01", "2026-01-05", freq="D"))call produces a plot with x axis ticks formatted for datetimes, see attached. I'd like the timedelta call to result in a plot with x axis ticks formatted for timedeltas, in a similar vein.jayaprajapatii commentedon Feb 22, 2026
@kdpenner Thanks for the clarification. I understand the goal is not just to avoid failure, but to have
ax.histhandle timedeltas with proper axis formatting, similar to datetimes. I'll investigate how datetime unit conversion is integrated inhistand whether the same units mechanism can be extended to timedeltas.scottshambaugh commentedon Feb 26, 2026
Timedeltas are not handled well in general, and I'm a little skeptical that just fixing the crash will give expected results. @jayaprajapatii, could you please share what a histogram looks like with your fix applied?
Relevant issue tracking timedelta things: #8869
jayaprajapatii commentedon Feb 27, 2026
With the current patch,
numpy.timedelta64values are normalized to days before range estimation and binning. The histogram renders without crashing, and bin positions correspond to day values.This change strictly addresses the crash caused by comparison with
np.inf, and enables basic histogram computation fortimedelta64inputs.It does not yet integrate with matplotlib's unit conversion system , so the axis is displayed as numeric day values rather than a timedelta-aware formatter.
If the preferred direction is to support full timedelta unit handling (as in #8869), I 'd happy to explore integrating this more deeply with the unit conversion machinery instead of converting to floats.
timhoffm commentedon Feb 27, 2026
We at least in some places accept timedelta, e.g.
plt.bar(['A', 'B', 'C'], np.array([1, 2, 4], dtype=np.timedelta64)).I'm not clear whether this is just an implicit
array.astype(float)(and whether that's generally sufficient) or whether we need more systematic unit handling.oscargus commentedon Feb 27, 2026
I do not think that the approach in #31293 is the correct one. Instead, I would use a different computation of xmin and xmax when we have timedelta64. np.min and np.max should The rest will probably "just work".
Also, there is no need to ravel/flatten. "The default is to compute the minimum of the flattened array."
oscargus commentedon Feb 27, 2026
Also, note that the whole point of the
if bin_range is None:check is to figure out if there are finite elements in x and in that case output a range. The only case it will not return a newbin_rangeis if the array is empty or only consists of nans.kdpenner commentedon Feb 27, 2026
that's what I had in mind if I were to fix this issue. grab the unit of the timedelta sequence---require all timedeltas in the sequence to have the same unit---and use, instead of infinity, a 64 bit integer with that unit for the max. but I didn't investigate if that moves to an error deeper in the stack.
scottshambaugh commentedon Feb 27, 2026
There are multiple issues with the bar plot above. Inconsistent bar widths, improper tick labels, and poor tick placement. IMO the timedelta improvements should be split into chunks, worked in a feature branch, and merged all at once they're in a good state. I think tackling this piecemeal will lead to more confusion & potential API lock-in than it's worth.
kdpenner commentedon Feb 28, 2026
the inconsistent bar widths and poor tick placement are not @jayaprajapatii 's issues to solve, imo. that plot happens to be what you see if you do
ax.hist([1, 2, 5, 7])without any further refinement.scottshambaugh commentedon Feb 28, 2026
Ah, it wasn't clear to me that the first wide bar was two bars adjacent to each other.
Still, I think timedelta compatibility is better handled all at once. We're silently converting to days and showing those results, and I think it's actually better to crash out than show misleading data (or for a stopgap, raise a more meaningful error). The workaround for a user with
.total_seconds()is simple until we get there.jayaprajapatii commentedon Feb 28, 2026
Thankyou all !,
To clarify my earlier changes:
DTypePromotionErrortriggered by comparisions withnp.infduringxmin/xmaxinitilization. While this resolves the crash, it implicitly alters unit semantics, which appears undesirable given the broader timedelta discussion.ravel()addition was meant to ensure consistent range computation across nested inputs. However , sincenp.min/np.maxalready operate on the flattened array by default, this change is redundant and I will remove it.From these discussions, what I understand is silently normalizing timedeltas to days is not ideal, and float casting may not be the right direction.
So, I propose to remove both changes and instead refractor the
xmin/xmaxcomputation to avoid comparisons withnp.infwhen handlingtimedelta64relying directly onnp.min/np.max.This keeps the scope limited to fixing the crash without introducing implicit normalization, altering unit semantics or expanding timedelta support.
If the preference is instead to raise a clearer error until full timedelta support is implemented, I can adjust accordingly.