pythonmatplotlibmatplotlib-animationmatplotlib-widget

Matplotlib changing underlying data for scatter plot with widget buttons


I have a plot in which I want to plot the following two data sets

x1,y1 = np.random.normal(0,1, (2,20)) # dataset 1
x2,y2 = np.random.normal(0,1, (2,20))

# Next, I create a plot and the PathCollection  from the scatter
fig, ax = plt.subplots()
ax = plt.gca()
p =  ax.scatter(x1, y1)

# I create two functions, each set the data using a different data set
def set_data1(event):
    p.set_offsets(x1, y2)
    plt.draw()
    
def set_data2(event):
    p.set_offsets(x2, y2)
    plt.draw()

# Location for the buttons
btn_1_loc = fig.add_axes( [0.02, 0.90, 0.2, 0.075])
btn_2_loc = fig.add_axes( [0.02, 0.80, 0.2, 0.075])

# Now, actually add the buttons
btn_1 = Button(btn_1_loc, 'Button 1')
btn_1.on_clicked(set_data1)

btn_2 = Button(btn_2_loc, 'Button 2')
btn_2.on_clicked(set_data2)

This creates a plot, with buttons. When I click the buttons, the data is not changed. If instead I change the color of the points with p.set_facecolor(color1) and color2, the plot does change and update.

How do I change the (x,y) location of my points using these two buttons?

enter image description here


Solution

  • set_offsets takes a 2D array, you're passing 2 individual arrays.

    Solution:

    def set_data1(event):
        p.set_offsets(np.column_stack((x1, y1)))
        plt.draw()
    
    def set_data2(event):
        p.set_offsets(np.column_stack((x2, y2)))
        plt.draw()