Skip to content

[ENH]: Provide Alternative to deprecated RectangleSelector(drawType='line') #22682

Closed

Description

@ianhi

Problem

There is no widget that is just two points connected by a line that is nicely draggable. This can be achieved using a rectangleSelector with two points and drawtype=line. But that has been (reasonably deprecated).

Proposed solution

Add a new widget DraggableLine that allows you to:

  1. Drag either handle independently
  2. translate the whole widget by grabbing the center line

Alternatively, I would have expected ToolHandles to be the owner of more of the handle dragging logic. That logic could be moved from the various selectors into the toolhandle (perhaps with appropriate callbacks) thus making ToolHandles much more general.

Activity

  1. ianhi commented on Mar 22, 2022

    @ianhi
    ContributorAuthor

    Deprecated in #19934

    also cc @dstansby and @ericpre (In my mind the main selector people)

  2. ianhi commented on Mar 22, 2022

    @ianhi
    ContributorAuthor

    Here's a minimal example of what I'm looking for. Could be improved with better styling options and an option to hold a key (e.g. shift/ctrl) to snap horizontally or vertically depending on the current angle. Also needs callbacks but otherwise pretty much this. Thoughts on adding to the widgets?

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.widgets import AxesWidget
    from numbers import Number
    from matplotlib.backend_bases import MouseEvent
    from matplotlib.lines import Line2D
    
    
    class DraggableLine(AxesWidget):
        def __init__(self, ax, x, y, grab_range=10, useblit=False, **kwargs) -> None:
            """
            ax : Axes
            x, y : (2,) Array of float
                The initial positions of the handles.
            grab_range : Number, default: 10
                Grab range for the handles in pixels (I think it's pixels)
            useblit : bool, default False
                Whether to use blitting for faster drawing (if supported by the
                backend). See the tutorial :doc:`/tutorials/advanced/blitting`
                for details.
            **kwargs :
                Passed on to Line2D for styling
            """
            super().__init__(ax)
            self._useblit = useblit
            center_x = (x[0] + x[1]) / 2
            center_y = (y[0] + y[1]) / 2
    
            self._handles = Line2D(
                [x[0], center_x, x[1]], [y[0], center_y, y[1]], marker="o"
            )
            # self._center_handle = Line2D([center_x], [center_y], marker='s', linestyle='none', pick=True)
            self.ax.add_artist(self._handles)
            # self.ax.add_artist(self._center_handle)
            self.connect_event("button_press_event", self._on_press)
            self.connect_event("motion_notify_event", self._on_move)
            self.connect_event("button_release_event", self._on_release)
            self._handle_idx = None  # none implies not moving
            self._grab_range = grab_range
    
        @property
        def grab_range(self) -> Number:
            """
            Grab range in pixels (I think in pixels)
            """
            return self._grab_range
    
        @grab_range.setter
        def grab_range(self, val: Number):
            if not isinstance(val, Number):
                raise TypeError(f"Val must be a number but got type {type(val)}")
            self._grab_range = val
    
        def _on_press(self, event: MouseEvent):
            if self.ax != event.inaxes:
                return
            if not self.canvas.widgetlock.available(self):
                return
            x, y = self._handles.get_data()
            # figure out if any handles are being grabbed
            # maybe possibel to do this with a pick event?
    
            x, y = self._handles.get_data()
            # this is taken pretty much directly from the implementation
            # in matplotlib.widget.ToolHandles.closest
            pts = self.ax.transData.transform(np.column_stack([x, y]))
            diff = pts - [event.x, event.y]
            dist = np.hypot(*diff.T)
            idx = np.argmin(dist)
            if dist[idx] < self._grab_range:
                self._handle_idx = idx
            else:
                self._handle_idx = None
    
        def _on_move(self, event: MouseEvent):
            if self.ax != event.inaxes:
                return
            if self._handle_idx is None:
                # not dragging one of out handles
                return
            x, y = self._handles.get_data()
            if self._handle_idx == 1:
                x += event.xdata - x[1]
                y += event.ydata - y[1]
            else:
                x[self._handle_idx] = event.xdata
                y[self._handle_idx] = event.ydata
                x[1] = (x[0] + x[2]) / 2
                y[1] = (y[0] + y[2]) / 2
            self._handles.set_data(x, y)
            self.ax.figure.canvas.draw_idle()
    
        def _on_release(self, event: MouseEvent):
            self._handle_idx = None
  3. ianhi commented on Mar 22, 2022

    @ianhi
    ContributorAuthor
  4. ianhi commented on Jun 17, 2022

    @ianhi
    ContributorAuthor

    Now in a pip installable package: pip install mpl-draggable-line https://mpl-draggable-line.readthedocs.io/en/stable/index.html

    so i'm gonna close. Would also be happy to integrate into the core mpl widgets if people think that would be preferable

  5. ericpre commented on Jun 18, 2022

    @ericpre
    Member

    This is nice!
    I am wondering if it would be possible to extend it to also fix #9608, by introducing a "vector widget": the line would need to be changed to an arrow style and the order of the selected point will kept, i.e. not sorted numerically.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions