1

I'm aware of several related questions on updating plots in while loops but they did not fully address my question.

I would like to expose - as simply as possible - a method I can call to update a plot when new data is available. The specific context is that I want histograms of parameters to update after some set number of iterations inside a training loop for a model.

When I say as simple as possible - for how infrequently I'm updating the plot I'm perfectly okay with simply closing and redrawing a new plot. Unfortunately I couldn't get that to work - as the training loop ran many separate figure windows were spawned and none displayed anything until the loop terminated.

The first thing I tried was to create a class with an update method for the plot like this:

class ParamPlot(object):

def __init__(self, model):
    self.model = model
    # model.param_classes is a list different sets of parameters
    n_param_classes = len(model.param_classes)
    self.fig, self.ax_arr = plt.subplots(nrows=n_param_classes)


def update(self):
    plt.clf()
    for params, axis in zip(model.param_classes, self.ax_arr):
        # assume that params is an array
        axis.hist(params, bins=250, normed=True)
    self.fig.canvas.draw()

But this resulted in a large number of figure windows being spawned, none of which displayed anything until the loop terminated.

How can I accomplish this?

rueberger
  • 121
  • 1
  • 1
  • 7

1 Answers1

0

Here's how I got it working (following how to update a plot figure?

class ParamPlot(object):

def __init__(self, model):
    self.model = model
    # model.param_classes is a list different sets of parameters
    n_param_classes = len(model.param_classes)
    self.fig, self.ax_arr = plt.subplots(nrows=n_param_classes)


def update(self):
    for axis in np.ravel(self.ax_arr):
        axis.clear()
    for params, axis in zip(model.param_classes, self.ax_arr):
        # assume that params is an array
        axis.hist(params, bins=250, normed=True)
    plt.draw()

Notice that clearis called on each axis.

It's not fast, but it's simple and it works.

Community
  • 1
  • 1
rueberger
  • 121
  • 1
  • 1
  • 7