0

I would like:

  1. A plot with a function : f(x,y) -> (x² + y²)/20

  2. A set of points (x, y, f(x,y)) that evolve over time.

To solve this problem I tried to clear the plot and update it at each iteration but I did not manage to do it...

Here's my code:

def parabole(x, y):
    return (x * x + y * y)/10

x = np.linspace(-10, 10, 30)
y = np.linspace(-10, 10, 30)
X, Y = np.meshgrid(x, y)
Z = parabole(X, Y)
for swarm in history:
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='jet', edgecolor='none')
    for particle in swarm:
         ax.scatter(particle[0], particle[1], particle[2])
    plt.show()
    plt.clf()

history is a list containing different state of my particle swarm. My particle swarm is a list of points (x, y, f(x,y))

How do I clear a plot at each iteration of the loop, and then plot the whole thing again in the same figure?

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
  • 1
    are you trying to make an animation? https://matplotlib.org/stable/api/animation_api.html – Karina Jul 28 '21 at 12:12
  • If I got your question correctly, you can do it following the answers here: [stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function](https://stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function) – wagnifico Jul 28 '21 at 18:16

1 Answers1

0

First you should take this line outside of the loop:

  fig = plt.figure()

Secondly, instead using these two lines:
 plt.show()
 plt.clf()

you should use:
 fig.canvas.draw()
 fig.canvas.flush_events()

Also, add this line to run GUI event loop: (You can also look at the link: https://www.geeksforgeeks.org/how-to-update-a-plot-on-same-figure-during-the-loop/)
  plt.ion()

Finally your code should look line this:


def parabole(x, y):
  return (x * x + y * y)/10

x = np.linspace(-10, 10, 30)
y = np.linspace(-10, 10, 30)
X, Y = np.meshgrid(x, y)
Z = parabole(X, Y)

plt.ion()
fig = plt.figure()

for swarm in history:
  ax = plt.axes(projection='3d')
  ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='jet', edgecolor='none')
  for particle in swarm:
   ax.scatter(particle[0], particle[1], particle[2])
  fig.canvas.draw()
  fig.canvas.flush_events()
  time.sleep(0.1) # You can also add this to observe the changes