Matplotlib updating live plot
<p>I want to update a line plot with matplotlib and wonder, if there is a good modification of the code, such that the line plotted simply gets updated instead of getting redrawn every time. Here is a sample code:</p>

<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
matplotlib.style.use('ggplot')

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

i=0
df = pd.DataFrame({"time": [pd.datetime.now()], "value": 0}).set_index("time")
plt.plot(df);

while True:
    temp_y=np.random.random();
    df2 = pd.DataFrame({"time": [pd.datetime.now()], "value": temp_y}).set_index("time")
    df = df.append(df2)
    plt.plot(df)
    i+=1
    plt.show()
    plt.pause(0.000001) 
</code></pre>

<p>As you see, the plotting gets slower and slower after a while and I think the line chart is redrawn every iteration since it changes colours. </p>

<p>Yes.</p>

<pre><code>x = np.arange(10)
y = np.random.rand(10)

line, = plt.plot(x,y)
line.set_data(x,np.random.rand(10))
plt.draw()
</code></pre>

<p>However, your plotting gets slower because your are extending your data frame and each append operation presumably copies that frame in memory to a new location. As your data frame increases in size, that copy operation takes longer. I would loop over an index and plot that (<code>for ii in range(len(data)): line.set_data(x[:ii], y[:ii])</code>)</p>

<p>EDIT: </p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd

n = 100
x = np.arange(n)
y = np.random.rand(n)
# I don't get the obsession with pandas...
df = pd.DataFrame(dict(time=x, value=y))

# initialise plot and line
line, = plt.plot(df['time'], df['value'])

# simulate line drawing
for ii in range(len(df)):
    line.set_data(df['time'][:ii], df['value'][:ii]) # couldn't be bothered to look up the proper way to index in pd
    plt.draw()
    plt.pause(0.001)
</code></pre>

python matplotlib plot while-loop