Home > OS >  is it possible to only update y-axis plot onclick?
is it possible to only update y-axis plot onclick?

Time:01-20

I'm using matplotlib to plot the specific values (x and y) from a numpy array list. I want to only edit the y-values while keeping the x-values the same (let's say only edit the y-value on click), but I can't seems to figure out how to.

I have tried

def oncick(event):
    if event.button == 1:
        x.append(event.xdata)
        y.append(event.ydata)
    #clear frame
    plt.cla()
    plt.plot(x, y, linestyle = "-", lw= 5, color = "#FF4500")
    plt.draw()
fig.canvas.mpl_connect("button_press_event", onclick)
plt.show()

but it ends up redrawing from the latest x-axis (appending to add a new value) and when I remove x.append(event.xdata) I got "ValueError: x and y must have same first dimension" error

CodePudding user response:

No need to append to your data or to clear the axes. We can create the data, create a line artist with your data and simply update everything upon click.

I am using np.searchsorted to find which index corresponds to where you clicked. Then, we change the y array at that index and replace the old value with the new value from the click event: event.ydata.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.sin(x)**2
fig, ax = plt.subplots()
line, = ax.plot(x, y, linestyle = "-", lw= 5, color = "#FF4500")

def on_click(event):
    if not event.inaxes: 
        return # Do nothing if the click is outside the ax.
    if event.button == 1:
        n = np.searchsorted(x, event.xdata)
        y[n] = event.ydata
        line.set_data(x, y)
        fig.canvas.draw()
    
fig.canvas.mpl_connect("button_press_event", on_click)
plt.show()

enter image description here

After a few clicks:

enter image description here

  • Related