Skip to content

[Bug]: ax.hist() fails on sequence of timedeltas due to comparison with np.inf #31182

Closed

Description

@kdpenner

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

  1. jayaprajapatii commented on Feb 21, 2026

    @jayaprajapatii
    Contributor

    Hii
    I reproduce this issue on current main.

    Environment:

    • Python 3.12
    • Linux (Ubuntu)
    • Matplotlib built from source

    The failure occurs during histogram range computation in Axes.hist , where xmin = np.inf and xmax = -np.inf are initialized and later compared against numpy.timedelta64. After _process_unit_info and convert_xunits, the data still contains timedelta64, so the min/max logic involving np.inf triggers the DTypePromotionError.

    I'm looking into adjusting the range computataion to avoid comparisons with np.inf for non-numeric dtypes.

  2. joddeepesh-cloud commented on Feb 22, 2026

    @joddeepesh-cloud
    Contributor

    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.

  3. jayaprajapatii commented on Feb 22, 2026

    @jayaprajapatii
    Contributor

    @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.

  4. kdpenner commented on Feb 22, 2026

    @kdpenner
    ContributorAuthor

    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.

    Image
  5. jayaprajapatii commented on Feb 22, 2026

    @jayaprajapatii
    Contributor

    @kdpenner Thanks for the clarification. I understand the goal is not just to avoid failure, but to have ax.hist handle timedeltas with proper axis formatting, similar to datetimes. I'll investigate how datetime unit conversion is integrated in hist and whether the same units mechanism can be extended to timedeltas.

  6. scottshambaugh commented on Feb 26, 2026

    @scottshambaugh
    Contributor

    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

  7. jayaprajapatii commented on Feb 27, 2026

    @jayaprajapatii
    Contributor
    Image

    With the current patch, numpy.timedelta64 values 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 for timedelta64 inputs.
    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.

  8. timhoffm commented on Feb 27, 2026

    @timhoffm
    Member

    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.

  9. oscargus commented on Feb 27, 2026

    @oscargus
    Member

    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."

  10. oscargus commented on Feb 27, 2026

    @oscargus
    Member

    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 new bin_range is if the array is empty or only consists of nans.

  11. kdpenner commented on Feb 27, 2026

    @kdpenner
    ContributorAuthor

    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.

  12. scottshambaugh commented on Feb 27, 2026

    @scottshambaugh
    Contributor

    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.

  13. kdpenner commented on Feb 28, 2026

    @kdpenner
    ContributorAuthor

    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.

  14. scottshambaugh commented on Feb 28, 2026

    @scottshambaugh
    Contributor

    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.

  15. jayaprajapatii commented on Feb 28, 2026

    @jayaprajapatii
    Contributor

    Thankyou all !,

    To clarify my earlier changes:

    • The float casting(normalizing to days was introduced to avoid the DTypePromotionError triggered by comparisions with np.inf during xmin/xmax initilization. While this resolves the crash, it implicitly alters unit semantics, which appears undesirable given the broader timedelta discussion.
    • The ravel() addition was meant to ensure consistent range computation across nested inputs. However , since np.min/np.max already 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/xmax computation to avoid comparisons with np.inf when handling timedelta64 relying directly on np.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.

  16. added this to the v3.11.0 milestone on Mar 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions