Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Improving error message for width and position type mismatch in violi…
…nplot
  • Loading branch information
hasanrashid committed Oct 13, 2025
commit 1e2bcae3e50a0b63950b017d4aea45593eeb1e7d
15 changes: 15 additions & 0 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import datetime
import functools
import itertools
import logging
Expand Down Expand Up @@ -9047,6 +9048,20 @@ def violin(self, vpstats, positions=None, vert=None,
elif len(widths) != N:
raise ValueError(datashape_message.format("widths"))

# Proactive validation: if positions are datetime-like
# widths must be timedelta-like.
if any(isinstance(p, (datetime.datetime, datetime.date))
for p in positions):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it enough to check the first position? I think mixed positions are not allowed anyway. Also, do we need to handle np.datetime64 arrays?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hasanrashid You've marked this as resolved. Please comment how my above questions are addressed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timhoffm Yes, it is enough to check the first position. The position argument can't mix datetime with float. width can't mix timedelta and float either.

I was approaching this by converting entries into numeric equivalent until it was suggested that I provide clearer message instead.

Also, yes, datetime64 isn't needed either. I was thinking of all test cases, but I realize datetime64 isn't a supported type in violinplot.

Making the adjustments

@timhoffm timhoffm Sep 21, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is datetime64 not supported? Should we rather fix this? (Can be later, but already add the check here?)

@hasanrashid hasanrashid Sep 28, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timhoffm

If I try a testcase like this:

def test_np_datetime64_positions_with_float_widths_behaves_like_numeric():
    """Test that np.datetime64 positions with float widths do not raise TypeError (treated as numeric)."""
    fig, ax = plt.subplots()
    try:
        vpstats = violin_plot_stats()
        positions = [np.datetime64('2020-01-01'), np.datetime64('2021-01-01')]
        widths = [0.5, 1.0]
        # Should not raise TypeError, but may raise downstream if not supported
        ax.violin(vpstats, positions=positions, widths=widths)
    finally:
        plt.close(fig)

This produces the following error:
numpy._core._exceptions._UFuncBinaryResolutionError: ufunc 'add' cannot use operands with types dtype('float64') and dtype('<M8[D]')

I took this to mean that datetime64 was not an expected type of datetime for biolinplots- thus unsupported.

If we need to investigate adding datetime64 support in violineplot, should it be another issue? We are updating the error message enforcing timedelta with datetimes; datetime64 support- to me- seems like it should be investigated in a separate issue (which I am happy to open and work on)

_widths = widths if not np.isscalar(widths) else [widths] * N
Comment thread
hasanrashid marked this conversation as resolved.
Outdated
if any(not isinstance(w, (datetime.timedelta, np.timedelta64))
for w in _widths):
raise TypeError(
"If positions are datetime/date values, pass widths as "
"datetime.timedelta (e.g., datetime.timedelta(days=10))"
"or numpy.timedelta64."
)

Comment thread
hasanrashid marked this conversation as resolved.
Outdated

# Validate side
_api.check_in_list(["both", "low", "high"], side=side)

Expand Down
95 changes: 95 additions & 0 deletions lib/matplotlib/tests/test_violinplot_datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
Unit tests for proactive validation of datetime
positions and timedelta widths in violinplot.
"""

import datetime
import pytest

import matplotlib.pyplot as plt


def make_vpstats():
"""Create minimal valid stats for a violin plot."""


Comment thread
hasanrashid marked this conversation as resolved.
Outdated
def violin_plot_stats():
# Stats for violin plot
datetimes = [
datetime.datetime(2023, 2, 10),
datetime.datetime(2023, 5, 18),
datetime.datetime(2023, 6, 6)
]
return [{
'coords': datetimes,
'vals': [0.1, 0.5, 0.2],
'mean': datetimes[1],
'median': datetimes[1],
'min': datetimes[0],
'max': datetimes[-1],
'quantiles': datetimes
}, {
'coords': datetimes,
'vals': [0.2, 0.3, 0.4],
'mean': datetimes[2],
'median': datetimes[2],
'min': datetimes[0],
'max': datetimes[-1],
'quantiles': datetimes
}]


def test_datetime_positions_with_float_widths_raises():
"""Test that datetime positions with float widths raise TypeError."""
fig, ax = plt.subplots()
try:
vpstats = violin_plot_stats()
positions = [datetime.datetime(2020, 1, 1), datetime.datetime(2021, 1, 1)]
widths = [0.5, 1.0]
with pytest.raises(TypeError,
match="positions are datetime/date.*widths as datetime\\.timedelta"):
ax.violin(vpstats, positions=positions, widths=widths)
finally:
plt.close(fig)
Comment thread
timhoffm marked this conversation as resolved.
Outdated


def test_datetime_positions_with_scalar_float_width_raises():
"""Test that datetime positions with scalar float width raise TypeError."""
fig, ax = plt.subplots()
try:
vpstats = violin_plot_stats()
positions = [datetime.datetime(2020, 1, 1), datetime.datetime(2021, 1, 1)]
widths = 0.75
with pytest.raises(TypeError,
match="positions are datetime/date.*widths as datetime\\.timedelta"):
ax.violin(vpstats, positions=positions, widths=widths)
finally:
plt.close(fig)


def test_numeric_positions_with_float_widths_ok():
"""Test that numeric positions with float widths work."""
fig, ax = plt.subplots()
try:
vpstats = violin_plot_stats()
positions = [1.0, 2.0]
widths = [0.5, 1.0]
ax.violin(vpstats, positions=positions, widths=widths)
finally:
plt.close(fig)


def test_mixed_positions_datetime_and_numeric_behaves():
"""Test that mixed datetime and numeric positions
with float widths raise TypeError.
"""
fig, ax = plt.subplots()
try:
vpstats = violin_plot_stats()
positions = [datetime.datetime(2020, 1, 1), 2.0]
widths = [0.5, 1.0]
with pytest.raises(TypeError,
match="positions are datetime/date.*widths as datetime\\.timedelta"):
ax.violin(vpstats, positions=positions, widths=widths)
finally:
plt.close(fig)