Editing wave with mouse clicking

I just want to know why my function on_pick is not working when I click the mouse + why there is no any output as it should be !!!

import numpy as np
import matplotlib.pyplot as plt

# Generate an array of time values with 1000 points and a duration of 1 second
time = np.linspace(0, 1, 1000)

# Generate a sine wave with a frequency of 10 Hz and an amplitude of 1
waveform = np.sin(2 * np.pi * 10 * time)

# Create a figure and set up the plot
fig, ax = plt.subplots()
ax.set_xlabel("Time (s)")

def on_pick(event):
    #Just want to know if the fun is working properly
    print("Hello I'm working")
    # Get the x coordinate of the mouse click
    x = event.mouseevent.xdata

    # Remove the data at the x coordinate
    waveform[int(x * len(time))] = 0
    # Update the plot with the modified waveform data
    ax.plot(time, waveform)

# Enable the pick_event feature
fig.canvas.mpl_connect('pick_event', on_pick)

# Plot the initial waveform data
ax.plot(time, waveform)

# Show the plot

It appears that the picker argument is required in the plot call to specify a tolerance for the pick.

I changed your code to include that

ax.plot(time, waveform, picker=5)

and get into the event handler when I pick on or very near the curve. I suspect if you set it to something huge, you can pick anywhere.

1 Like

I came up with another whole code to solve this issue but the idea here I want the modification to occur on the same plot, not a new figure!!

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backend_bases import MouseButton
# Generate a sine wave with a frequency of 1 Hz and a duration of 5 seconds
t = np.linspace(0, 5, 500)
y = np.sin(2*np.pi*t)
plt.plot(t, y)

# Capture mouse clicks on the plot

points = plt.ginput(4)

# Get the x-coordinates of the mouse clicks
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
x4, y4 = points[3]

# Find the indices of the waveform signal that correspond to the x-coordinates
i1 = np.argmin(np.abs(t - x1))
i2 = np.argmin(np.abs(t - x2))
i3 = np.argmin(np.abs(t - x3))
i4 = np.argmin(np.abs(t - x4))
# Set the values of the waveform between the two mouse clicks to zero
y[i1:i4+1] = 0
plt.plot(t, y)
# Plot the modified waveform