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

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
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):
Comment on lines +9053 to +9054
Copy link
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?

_widths = widths if not np.isscalar(widths) else [widths] * N
Copy link
Member

Choose a reason for hiding this comment

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

This is only used to do the instance check. We don't need to do this N times on the the same instance.

Suggested change
_widths = widths if not np.isscalar(widths) else [widths] * N
_widths = widths if not np.isscalar(widths) else [widths]

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


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


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)


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)
Loading