-
-
Notifications
You must be signed in to change notification settings - Fork 8k
Improving error message for width and position type mismatch in violinplot #30545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hasanrashid
wants to merge
1
commit into
matplotlib:main
Choose a base branch
from
hasanrashid:enh-30417
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+110
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,3 +1,4 @@ | ||||||
import datetime | ||||||
import functools | ||||||
import itertools | ||||||
import logging | ||||||
|
@@ -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): | ||||||
_widths = widths if not np.isscalar(widths) else [widths] * N | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
||||||
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) | ||||||
|
||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?