0

I have the following code snippet:

import numpy as np
import matplotlib.pyplot as plt

N = 25
M = 10

def aFuncation(x):
    return np.random.normal(100*np.exp(-x), 10.0)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = np.zeros(N)
ys = np.zeros(N)
stds = np.zeros(N)

for n in range(N):
    avgC = np.zeros(M)
    for m in range(M):
        Cost = aFuncation(n)
        avgC[m] = Cost

    xs[n] = n
    ys[n] = np.mean(avgC)
    stds[n] = np.std(avgC)

    # Plot the time series
    ax.clear()
    ax.fill_between(xs[:n], ys[:n] - stds[:n], ys[:n] + stds[:n], alpha=0.3, color='black')
    ax.plot(xs[:n], ys[:n], color='red')
    ax.set_xlim([0, N + 1])
    ax.set_xlabel('Number of evolutions')
    ax.set_ylabel('Expected future cost')

    plt.show()

I am not sure why the plot is not updated after the first iteration (n=1). I have read several posts related to this topic. The posts suggest the use of plt.ion(), plt.clf(), plt.draw(), etc. Whenever more I read about this topic, I become more confused. I am unfortunately unable to find a solution to this problem.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
mdslt
  • 155
  • 1
  • 10
  • Maybe replacing `plt.show()` with `plt.pause(1)` works for you? If you are running in a Jupyter notebook, you might need to set matplotlib interactive (`%matplotlib inline` only allows still images; `%matplotlib notebook` might work in your case, depending on how Jupyter is installed) – JohanC Jan 23 '22 at 22:10
  • I assume you just want the plot and not an animation. In which case you should take plot.show() out of your loop (i.e. unindent it). Calling plot.show() stops your code and will not execute the rest. – tgpz Jan 23 '22 at 22:47
  • @JohanC, replacing `plt.show()` with `plt.pause(1)` did not help. I am using PyCharm on Windows. – mdslt Jan 23 '22 at 22:52
  • @tgpz, I would like to update the plot at each iteration of `n`. If I remove `plt.show()` from the loop, it does not even generate the plot until the loop related to `n` is over. – mdslt Jan 23 '22 at 22:54
  • Does this answer your question? [Matplotlib animation not displaying in PyCharm](https://stackoverflow.com/questions/50928743/matplotlib-animation-not-displaying-in-pycharm) – Jody Klymak Jan 24 '22 at 06:44
  • Your question asked is why the plot is stopping. The answer is given in the [docs](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html), stating that show() is blocking, i.e. that the rest of your code will not execute. If you meant to ask, "why is this code not an producing an animation?" the answer is that you have written code to generate a plot. Animation examples are available in the [documentation](https://matplotlib.org/stable/api/animation_api.html) or in the above comment by @JodyKlymak – tgpz Jan 24 '22 at 22:54

0 Answers0