Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

hasanrashid
Copy link
Contributor

PR summary

This PR intends to close [ENH]: Support using datetimes as positions argument to violin(...) #30417

It should be possible to set the position of a violin plot to be a datetime. Currently, an attempt to do this results in this error message: TypeError: unsupported operand type(s) for +: 'float' and 'datetime.datetime'

The error stems from trying to perform operations between float and datetime if datetime was provided as position arguments.

The proposed solution:

  • Converts datetimes in the "position" argument of a violin plot to float representation using date2num function in matplotlib.dates.
  • Converts any "width" argument in the form of time difference to days.

The violinplot tests in test_axes.py were successful

An example that tests both "width" and "positions":

Example:

import datetime
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
datetimes = [
    datetime.datetime(2023, 2, 10),
    datetime.datetime(2023, 5, 18),
    datetime.datetime(2023, 6, 6)
]
ax.violin(
    [
        {
            'coords': datetimes,
            'vals': [0.1, 0.5, 0.2],
            'mean': datetimes[1],
            'median': datetimes[1],
            'min': datetimes[0],
            'max': datetimes[-1],
            'quantiles': datetimes
        }
    ],
    positions=[datetime.datetime(2023, 1, 1)],
    widths=[datetime.timedelta(days=1)]
)

PR checklist

@rcomer
Copy link
Member

rcomer commented Sep 6, 2025

Hi @hasanrashid thank you for your work on this. I found that your example (and the example from #30417 (comment)) do actually work correctly with the main development branch. So I think we do not need to add this extra handling. Instead, I think we need to raise a more informative error for the original example from #30417: if the user passes datetimes for the positions, they must also pass timedeltas for the widths. Or, more generally, they must pass positions and widths that can be added to each other.

@hasanrashid
Copy link
Contributor Author

Sorry, I think I messed up the last commit. Cleaning it up

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[ENH]: Support using datetimes as positions argument to violin(...)
2 participants