Matplotlib returns empty plot

I have this python code:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

n = 100
x = np.random.randn(n)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-4,4,0.5)
    plt.hist(x[:curr],bins = bins)
    plt.gca().set_title('Samplng the Normal distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27])

fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval = 100)

      

It should update the bell graph every 3 draws, but when I run it, my plot is empty and nothing happens. Do you know, why?

Thank!

+3


source to share


2 answers


The code in the question is flawless. It refreshes the graph every 100 milliseconds.

My guess would be as follows. The fact that you are not using plt.show()

here, but can still see the plot, suggests that you are using it in an embedded environment. For example. you can use Jupyter and (intentionally or not) activate %matplotlib inline

. The built-in backend does not support animation (this is clear since it only shows the png image of the plot) and so the solution might be to use a different backend.

If in a jupiter laptop:

  • If you want to have animation inside the laptop, use %matplotlib notebook

    .
  • If you want to have animation inside notebook and use %matplotlib inline

    and have matplotlib 2.1 or newer, you can also use

    IPython.display import HTML
    HTML(ani.to_jshtml())
    
          

    to show the animation.

  • If you want to have animation as its own window use %matplotlib tk

    .


If you run the code as a script:

  • Add plt.show()

    to the end of the code.

If running in spyder

  • Make sure you are not using code in the built-in IPython console. Instead, run it in a new specialized python console.
    enter image description here
+2


source


You are missing plt.show()

at the end. With this instruction works for me.



+1


source







All Articles