简体   繁体   中英

PyPlot - Highlight point selected with picker

I'm plotting a time series using pyplot and want to highlight a point once it is selected (using a pick_event ). Found a similar problem here , but just can't get my head around it. This is a basic example of what I do:

import matplotlib.pyplot as plt

class MyPlot(object):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__()

    def makePlot(self):
        fig = plt.figure('Test', figsize=(10, 8))
        ax = plt.subplot(111)
        x = range(0, 100, 10)
        y = (5,)*10
        ax.plot(x, y, '-', color='red')
        ax.plot(x, y, 'o', color='blue', picker=5)
        plt.connect('pick_event', self.onPick)
        plt.show()

    def onPick(self, event=None):
        this_point = event.artist
        x_value = this_point.get_xdata()
        y_value = this_point.get_ydata()
        ind = event.ind
        print 'x:{0}'.format(x_value[ind][0])
        print 'y:{0}'.format(y_value[ind][0])

if __name__ == '__main__':
    app = MyPlot()
    app.makePlot()

The selected point shall be marked (eg by making it yellow), but when I pick another point, it shall be resetted back to blue and only the newly picked point shall be highlighted (no annotations, just the color change). How can I do this?

You can define a new plot (colored in yellow), which is empty at the beginning. Once you click a point, change the data of this plot to the data of the picked point and redraw the canvas.

import matplotlib.pyplot as plt

class MyPlot(object):

    def makePlot(self):
        self.fig = plt.figure('Test', figsize=(10, 8))
        ax = plt.subplot(111)
        x = range(0, 100, 10)
        y = (5,)*10
        ax.plot(x, y, '-', color='red')
        ax.plot(x, y, 'o', color='blue', picker=5)
        self.highlight, = ax.plot([], [], 'o', color='yellow')
        self.cid = plt.connect('pick_event', self.onPick)
        plt.show()

    def onPick(self, event=None):
        this_point = event.artist
        x_value = this_point.get_xdata()
        y_value = this_point.get_ydata()
        ind = event.ind
        self.highlight.set_data(x_value[ind][0],y_value[ind][0])
        self.fig.canvas.draw_idle()

if __name__ == '__main__':
    app = MyPlot()
    app.makePlot()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM