0
votes

I have a question about using fig, axes function in a loop in matplotlib. I am trying to create a few plots with multiple subplots (the number of subplots isn not fixed) in a loop as follows:

def start_plot(self):
    if self.running:
        run_fig, run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        hist_fig, hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        hist_ax[iwindow+1].hist(timeseries, label=window_name) 

plot = plot_class(run =1, hist =1, matrix = get_matrix(*args)) # e.g. matrix = (3,2)

for istrat, strat in enumerate(strats):
    plot.start_plot()
    for iwindow, window in enumerate(windows):
        plot.create_plots(iwindow, window)

Is there a way to make this work without having to return axes in function and pass it around? If I use plt.figure instead of fix,axes, then i can simply update any figure using plt.figure(fig_no).

1

1 Answers

0
votes

You can store run_fig and run_ax in your object as instance attributes and then access them from any other method of that object. This would be done using self.

Use self.run_fig, etc. in start_plot and create_signal_plots as in:

def start_plot(self):
    if self.running:
        self.run_fig, self.run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        self.hist_fig, self.hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        self.run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        self.hist_ax[iwindow+1].hist(timeseries, label=window_name)