Matplotlib / python clickable points

前端 未结 2 2009
小鲜肉
小鲜肉 2021-01-02 18:51

I have a bunch of time series data with points every 5 seconds. So, I can create a line plot and even smooth the data to have a smoother plot. The question is, is there any

2条回答
  •  耶瑟儿~
    2021-01-02 19:36

    If in case you want to bind extra property to your artist object, for example you are plotting IMDB ratings of several movies, and you want to see by clicking on a point which movie it corresponds to, you can do that by adding a custom object to the point that you plotted, like this:

    import matplotlib.pyplot as plt
    
    class custom_objects_to_plot:
        def __init__(self, x, y, name):
            self.x = x
            self.y = y
            self.name = name
    
    a = custom_objects_to_plot(10, 20, "a")
    b = custom_objects_to_plot(30, 5, "b")
    c = custom_objects_to_plot(40, 30, "c")
    d = custom_objects_to_plot(120, 10, "d")
    
    def on_pick(event):
        print(event.artist.obj.name)
    
    fig, ax = plt.subplots()
    for obj in [a, b, c, d]:
        artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
        artist.obj = obj
    
    fig.canvas.callbacks.connect('pick_event', on_pick)
    
    plt.show()
    

    Now when you click one of the points on the plot, the name property of the corresponding object will be printed.

提交回复
热议问题