2

I am trying to do something like this to have a closer look at my data:

What is the currently correct way to dynamically update plots in Jupyter/iPython?

Or here: https://nbviewer.jupyter.org/gist/branning/c8e63ce81be0391260b1

This is my code:

%matplotlib notebook
from matplotlib import pyplot as plt
import pandas as pd

START = DATA.index[0]
END = DATA.index[-1]
DT = "6H"

DATERANGE = pd.date_range(START, END, freq=DT)

fig, ax = plt.subplots(figsize(8, 6))
since = DATERANGE[0]
for till in DATERANGE[1:]:
    data = DATA['SOME_SERIES'].loc[since:till]
    if len(data) > 0:
        if ax.lines:
            ax.lines[0].set_xdata(data.index)
            ax.lines[0].set_ydata(data)
        else:
            ax.plot(data.index, data)
        upper, lower = data.min()*0.9, data.max()*1.1
        if not (isnan(upper) or isnan(lower)):
            ax.set_ylim((data.min()*0.9, data.max()*1.1))
        ax.set_xlim((data.index[0], data.index[-1]))
        fig.canvas.draw()
    time.sleep(2)
    since = till

My problem is that while the plot is updating it doesn't fill the canvas (hope I got the terminology right there) but is only about a quarter of the size. It looks like this:

Plot while looping

Only when the loop ended the plot gets bigger:

Plot after looping

This is also the case with the exact code from the links above.

I updated jupyter and matplotlib, I tried fig.tight_layout(), I also tried %matplotlib notebook %matplotlib nbagg but that didn't do the trick either..

Does anybody have a solution for this?

Thanks, Phillip

  • I was working from home via Microsoft Remote Desktop when the issue occured. Now I'm in the office and it is working like a charm... Where do I have to complain? :-D – milchmannverleih May 05 '20 at 12:45

1 Answers1

2

For me this was an issue when working on my Mac. There is an open issue on this; right now it seems that the best solution is to split the code into two cells. Shameless cross-copying of that solution:

# Cell 1
%matplotlib notebook
# OR: %matplotlib widget
import matplotlib.pyplot as plt
import numpy as np
import time

fig = plt.figure()

# Cell 2
for j in range(10):       
    plt.plot(range(0, j), [1/(i+1) for i in range(0, j)])
    fig.canvas.draw()
    time.sleep(.1)

Alternatively one could go for the "inline" backend. Of course that one is not interactive, and a bit uglier. See this thread

Patrick
  • 1,829
  • 19
  • 32