Skip to content

Request an inaxes method in Figure to calculate whether a point is in an axes. #9821

Closed

Description

@lkjell

Request an inaxes method in Figure to calculate whether a point is in an axes and return the axes. i.e.

def inaxes(self, xy):
    axes_list = [a for a in self.get_axes() if a.patch.contains_point(xy)]

    if len(axes_list) == 0:
        axes = None
    elif len(axes_list) > 1:  # Overlap, get the highest zorder
        axes_list.sort(key=lambda x: x.zorder)
        axes = axes_list[-1]  # Use the highest zorder
    else:
        axes = axes_list[0]

    return axes

Rational: This make it easier (in my opinion) to find a method that do the requested method. Alternative is to create a LocationEvent and use the inaxes attribute. Using the LocationEvent class may trigger axes_enter_event and axes_leave_event.

In any cases a good documentation on matplotlib's coordinate and how to convert different backends' coordinate to matplotlib, most of the time flip the y axis, is needed.

Activity

  1. anntzer commented on Nov 21, 2017

    @anntzer
    Contributor

    I guess the issue here is whether xy is in screen or data coordinates -- passing in a mouse event is unambiguous. If we do decide on one convention (it is easy to switch from one to the other using the correct transform), then I'd rather fix Artist.contains to support both mouse events or xy as inputs; and promote cbook._topmost_artist to be a public API, so that you can do something like

    cbook.topmost_artist([ax for ax in ... if ax.contains(xy)[0]])
    

    On the other hand, I don't think manually instantiating a LocationEvent is that bad, especially if the point is only to use it in internal implementations (and I don't understand your comment that I'd trigger an event -- AFAICT it won't?)

    LocationEvent("", fig.canvas, x, y)
    

    In general I don't think you need to manually bother with flipy, ax.transAxes/ax.transData should (I guess?) take care of it for you.

  2. lkjell commented on Nov 21, 2017

    @lkjell
    ContributorAuthor
        def _update_enter_leave(self):
            'process the figure/axes enter leave events'
            if LocationEvent.lastevent is not None:
                last = LocationEvent.lastevent
                if last.inaxes != self.inaxes:
                    # process axes enter/leave events
                    try:
                        if last.inaxes is not None:
                            last.canvas.callbacks.process('axes_leave_event', last)
                    except:
                        pass
                        # See ticket 2901582.
                        # I think this is a valid exception to the rule
                        # against catching all exceptions; if anything goes
                        # wrong, we simply want to move on and process the
                        # current event.
                    if self.inaxes is not None:
                        self.canvas.callbacks.process('axes_enter_event', self)
    
            else:
                # process a figure enter event
                if self.inaxes is not None:
                    self.canvas.callbacks.process('axes_enter_event', self)
    

    This method is called when LocationEvent is instantiate.

  3. anntzer commented on Nov 21, 2017

    @anntzer
    Contributor

    ouch.
    Good catch. This should probably be clearly documented too...

  4. lkjell commented on Nov 21, 2017

    @lkjell
    ContributorAuthor

    xy is the canvas coordinate, I believe is the figure.bbox. Data coordinates are the axes coordinate?

  5. anntzer commented on Nov 21, 2017

    @anntzer
    Contributor

    Axes coordinates mean 0-1, data coordinates mean xmin-xmax.

  6. lkjell commented on Nov 22, 2017

    @lkjell
    ContributorAuthor

    Need to pass in a coordinate which takes in pixel value (defaul) of the whole canvas or normalized [0,1] (keyword).

  7. added this to the milestone on Nov 22, 2017
  8. tacaswell commented on Nov 22, 2017

    @tacaswell
    Member

    @lkjell What are you doing that this came up?

  9. lkjell commented on Nov 22, 2017

    @lkjell
    ContributorAuthor

    Was working with some drag/drop to plot in qt5.

    A sample script if any is interested.

    import sys
    from math import ceil
    
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.gridspec import GridSpec
    from PyQt5 import QtWidgets
    
    
    class CanvasBase(FigureCanvas):
        """
        Frontend class. This is the FigureCanvas as well as plotting functionality.
        Plotting use pyqt5.
        """
    
        def __init__(self, parent=None):
            self.figure = Figure((8,6),100)
            super().__init__(self.figure)
    
            # self.canvas = self.figure.canvas
            self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
            self.updateGeometry()
            self.setParent(parent)
    
            self.setAcceptDrops(True)
    
            self.mpl_connect("figure_enter_event", lambda x: print("figure"))
            self.mpl_connect("axes_enter_event", lambda x: print("axes"))
    
        def inaxes(self, xy):
            axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy)]
    
            if axes_list:
                axes = max(reversed(axes_list), key=lambda x: x.zorder)
            else:
                axes = None
    
            return axes
    
        def add_axes(self, cols=1):
            N = len(self.figure.axes) + 1
            if N > 3:
                return self.figure.axes[-1]
            rows = int(ceil(N / cols))
            grid = GridSpec(rows, cols)
    
            for gs, ax in zip(grid, self.figure.axes):
                ax.set_position(gs.get_position(self.figure))
    
            self.figure.add_subplot(grid[N - 1])
    
            return self.figure.axes[-1]
    
        def remove_axes(self, cols=1):
            N = len(self.figure.axes) - 1
            if N < 0:
                return
    
            rows = int(ceil(N / cols))
            gridspec = GridSpec(rows, cols)
    
            ax = self.figure.axes.pop()
            self.figure.delaxes(ax)
    
            for gs, ax in zip(gridspec, self.figure.axes):
                ax.set_position(gs.get_position(self.figure))
    
        def clean_empty_axes(self):
            for axes in self.figure.axes:
                if len(axes.lines) == 0:
                    axes.remove()
    
            cols = 1
            N = len(self.figure.axes)
            rows = int(ceil(N / cols))
            grid = GridSpec(rows, cols)
    
            for gs, ax in zip(grid, self.figure.axes):
                ax.set_position(gs.get_position(self.figure))
    
        def dragEnterEvent(self, event):
            super().dragEnterEvent(event)
    
            print(event)
            # if event.mimeData().hasFormat("application/json"):
            #     event.acceptProposedAction()
    
            event.acceptProposedAction()
    
        def dropEvent(self, event):
            super().dropEvent(event)
    
            # self.msg = bytes(event.mimeData().data("application/json")).decode("utf-8")
            # self.msg = json.loads(self.msg, "utf-8")
    
            x, y = self.mouseEventCoords(event.pos())
            axes = self.inaxes((x, y))
    
            if axes is None:
                axes = self.add_axes()
    
            axes.plot(range(100))
    
            self.clean_empty_axes()
            self.draw_idle()
    
            event.acceptProposedAction()
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        mw = CanvasBase()
        mw.show()
        sys.exit(app.exec_())
    
  10. QuLogic commented on Aug 4, 2020

    @QuLogic
    Member

    Appears to be fixed by #9845.

  11. modified the milestones: needs sorting, v3.1.0 on Aug 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions