pythonarrayspython-3.xmatplotlibginput

How to slice list from matplotlib ginput


I have a list of values in Python, which I'm plotting with matplotlib. I'm then trying to use ginput in matplotlib to click two points on the graph, from which the X coordinates will be taken, between which to slice my original list. However, I can't seem to find a way to do this.

I already have a list of numbers called MIList, and the following code isn't working for me:

startinput = plt.ginput(2)
print("clicked", startinput)
startinputxvalues = [x[0] for x in startinput]
print(startinputxvalues)
x1 = startinputxvalues[0]
print(x1)
x2 = startinputxvalues[1]
print(x2)
slicedMIList = [MIList[int(x1):int(x2)]]
plt.plot(slicedMIList)

This gives me an array, but it doesn't plot these values on my graph - does anyone have any input as to what I'm doing wrong?

Thanks


Solution

  • The main point is that you need to redraw the canvas, once changes have been made to it. So in order for the new plot to become visible you can call

    plt.gcf().canvas.draw()
    

    Here is a complete working code:

    import matplotlib.pyplot as plt
    import numpy as np
    
    X = np.arange(10)
    Y = np.sin(X)
    plt.plot(X, Y)
    
    startinput = plt.ginput(2)
    x, y = zip(*startinput)
    
    Ysliced = Y[int(x[0]):int(x[1])+1]
    Xsliced = X[int(x[0]):int(x[1])+1]
    plt.plot(Xsliced, Ysliced, color="C3", linewidth=3)
    
    #draw the canvas, such that the new plot becomes visible
    plt.gcf().canvas.draw()
    
    plt.show()
    

    enter image description here