Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 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 @@ -9049,6 +9050,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.
Resolved
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.
Resolved

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

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1433,7 +1433,7 @@ def _from_ax_coords(cls, name, ax, xy, *args, **kwargs):
def __str__(self):
return (f"{self.name}: "
f"xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) "
f"button={self.button} dblclick={self.dblclick} "
f"button={self.button} dblclick={self.dblclick} step={self.step} "
f"inaxes={self.inaxes}")


Expand Down
4 changes: 4 additions & 0 deletions lib/matplotlib/dviread.py
Original file line number Diff line number Diff line change
Expand Up @@ -1347,8 +1347,12 @@ def _fontfile(cls, suffix, texname):
parser = ArgumentParser()
parser.add_argument("filename")
parser.add_argument("dpi", nargs="?", type=float, default=None)
parser.add_argument("-d", "--debug", action="store_true")
args = parser.parse_args()

if args.debug:
logging.basicConfig(level=logging.DEBUG)

def _print_fields(*args):
print(" ".join(map("{:>11}".format, args)))

Expand Down
66 changes: 66 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4112,6 +4112,72 @@ def test_violinplot_sides():
showextrema=True, showmedians=True, side=side)


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()
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(violin_plot_stats(), positions=positions, widths=widths)


def test_datetime_positions_with_scalar_float_width_raises():
"""Test that datetime positions with scalar float width raise TypeError."""
fig, ax = plt.subplots()
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(violin_plot_stats(), positions=positions, widths=widths)


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


def test_mixed_positions_datetime_and_numeric_behaves():
"""Test that mixed datetime and numeric positions
with float widths raise TypeError.
"""
fig, ax = plt.subplots()
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(violin_plot_stats(), positions=positions, widths=widths)


def test_violinplot_bad_positions():
ax = plt.axes()
# First 9 digits of frac(sqrt(47))
Expand Down
60 changes: 47 additions & 13 deletions lib/matplotlib/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from contextlib import ExitStack
import copy
import enum
import itertools
from numbers import Integral, Number

Expand Down Expand Up @@ -150,6 +151,10 @@ def ignore(self, event):
# docstring inherited
return super().ignore(event) or self.canvas is None

def _set_cursor(self, cursor):
"""Update the canvas cursor."""
self.ax.get_figure(root=True).canvas.set_cursor(cursor)


class Button(AxesWidget):
"""
Expand Down Expand Up @@ -2645,7 +2650,7 @@ def _handles_artists(self):
else:
return ()

def _set_cursor(self, enabled):
def _set_span_cursor(self, *, enabled):
"""Update the canvas cursor based on direction of the selector."""
if enabled:
cursor = (backend_tools.Cursors.RESIZE_HORIZONTAL
Expand All @@ -2654,7 +2659,7 @@ def _set_cursor(self, enabled):
else:
cursor = backend_tools.Cursors.POINTER

self.ax.get_figure(root=True).canvas.set_cursor(cursor)
self._set_cursor(cursor)

def connect_default_events(self):
# docstring inherited
Expand All @@ -2664,7 +2669,7 @@ def connect_default_events(self):

def _press(self, event):
"""Button press event handler."""
self._set_cursor(True)
self._set_span_cursor(enabled=True)
if self._interactive and self._selection_artist.get_visible():
self._set_active_handle(event)
else:
Expand Down Expand Up @@ -2714,7 +2719,7 @@ def direction(self, direction):

def _release(self, event):
"""Button release event handler."""
self._set_cursor(False)
self._set_span_cursor(enabled=False)

if not self._interactive:
self._selection_artist.set_visible(False)
Expand Down Expand Up @@ -2756,7 +2761,7 @@ def _hover(self, event):
return

_, e_dist = self._edge_handles.closest(event.x, event.y)
self._set_cursor(e_dist <= self.grab_range)
self._set_span_cursor(enabled=e_dist <= self.grab_range)

def _onmove(self, event):
"""Motion notify event handler."""
Expand Down Expand Up @@ -3147,6 +3152,13 @@ def onselect(eclick: MouseEvent, erelease: MouseEvent)
"""


class _RectangleSelectorAction(enum.Enum):
ROTATE = enum.auto()
MOVE = enum.auto()
RESIZE = enum.auto()
CREATE = enum.auto()


@_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace(
'__ARTIST_NAME__', 'rectangle'))
class RectangleSelector(_SelectorWidget):
Expand Down Expand Up @@ -3280,10 +3292,23 @@ def _press(self, event):
self._rotation_on_press = self._rotation
self._set_aspect_ratio_correction()

match self._get_action():
case _RectangleSelectorAction.ROTATE:
# TODO: set to a rotate cursor if possible?
pass
case _RectangleSelectorAction.MOVE:
self._set_cursor(backend_tools.cursors.MOVE)
case _RectangleSelectorAction.RESIZE:
# TODO: set to a resize cursor if possible?
pass
case _RectangleSelectorAction.CREATE:
self._set_cursor(backend_tools.cursors.SELECT_REGION)

return False

def _release(self, event):
"""Button release event handler."""
self._set_cursor(backend_tools.Cursors.POINTER)
if not self._interactive:
self._selection_artist.set_visible(False)

Expand Down Expand Up @@ -3327,9 +3352,20 @@ def _release(self, event):
self.update()
self._active_handle = None
self._extents_on_press = None

return False

def _get_action(self):
state = self._state
if 'rotate' in state and self._active_handle in self._corner_order:
return _RectangleSelectorAction.ROTATE
elif self._active_handle == 'C':
return _RectangleSelectorAction.MOVE
elif self._active_handle:
return _RectangleSelectorAction.RESIZE

return _RectangleSelectorAction.CREATE


def _onmove(self, event):
"""
Motion notify event handler.
Expand All @@ -3344,12 +3380,10 @@ def _onmove(self, event):
# The calculations are done for rotation at zero: we apply inverse
# transformation to events except when we rotate and move
state = self._state
rotate = 'rotate' in state and self._active_handle in self._corner_order
move = self._active_handle == 'C'
resize = self._active_handle and not move
action = self._get_action()

xdata, ydata = self._get_data_coords(event)
if resize:
if action == _RectangleSelectorAction.RESIZE:
inv_tr = self._get_rotation_transform().inverted()
xdata, ydata = inv_tr.transform([xdata, ydata])
eventpress.xdata, eventpress.ydata = inv_tr.transform(
Expand All @@ -3369,7 +3403,7 @@ def _onmove(self, event):

x0, x1, y0, y1 = self._extents_on_press
# rotate an existing shape
if rotate:
if action == _RectangleSelectorAction.ROTATE:
# calculate angle abc
a = (eventpress.xdata, eventpress.ydata)
b = self.center
Expand All @@ -3378,7 +3412,7 @@ def _onmove(self, event):
np.arctan2(a[1]-b[1], a[0]-b[0]))
self.rotation = np.rad2deg(self._rotation_on_press + angle)

elif resize:
elif action == _RectangleSelectorAction.RESIZE:
size_on_press = [x1 - x0, y1 - y0]
center = (x0 + size_on_press[0] / 2, y0 + size_on_press[1] / 2)

Expand Down Expand Up @@ -3429,7 +3463,7 @@ def _onmove(self, event):
sign = np.sign(xdata - x0)
x1 = x0 + sign * abs(y1 - y0) * self._aspect_ratio_correction

elif move:
elif action == _RectangleSelectorAction.MOVE:
x0, x1, y0, y1 = self._extents_on_press
dx = xdata - eventpress.xdata
dy = ydata - eventpress.ydata
Expand Down
4 changes: 4 additions & 0 deletions lib/matplotlib/widgets.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ from .figure import Figure
from .lines import Line2D
from .patches import Polygon, Rectangle
from .text import Text
from .backend_tools import Cursors

import PIL.Image

Expand Down Expand Up @@ -38,6 +39,7 @@ class AxesWidget(Widget):
def canvas(self) -> FigureCanvasBase | None: ...
def connect_event(self, event: Event, callback: Callable) -> None: ...
def disconnect_events(self) -> None: ...
def _set_cursor(self, cursor: Cursors) -> None: ...

class Button(AxesWidget):
label: Text
Expand Down Expand Up @@ -335,6 +337,7 @@ class SpanSelector(_SelectorWidget):
_props: dict[str, Any] | None = ...,
_init: bool = ...,
) -> None: ...
def _set_span_cursor(self, *, enabled: bool) -> None: ...
def connect_default_events(self) -> None: ...
@property
def direction(self) -> Literal["horizontal", "vertical"]: ...
Expand Down Expand Up @@ -398,6 +401,7 @@ class RectangleSelector(_SelectorWidget):
minspany: float
spancoords: Literal["data", "pixels"]
grab_range: float
_active_handle: None | Literal["C", "N", "NE", "E", "SE", "S", "SW", "W", "NW"]
def __init__(
self,
ax: Axes,
Expand Down
3 changes: 1 addition & 2 deletions requirements/doc/doc-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ ipywidgets
ipykernel
numpydoc>=1.0
packaging>=20
pydata-sphinx-theme~=0.15.0
mpl-sphinx-theme~=3.9.0
mpl-sphinx-theme~=3.10.0
pyyaml
PyStemmer
sphinxcontrib-svg2pdfconverter>=1.1.0
Expand Down
Loading