0

I've managed to set up dynamic graph of one variable in matplotlib:

def update_line(hl, new_data):

    hl.set_xdata(np.append(hl.get_xdata(), new_data[0]))
    hl.set_ydata(np.append(hl.get_ydata(), new_data[1]))
    plt.draw()


cost_plot, = plt.plot([], [], 'b-')
plt.xlabel('iter')
plt.ylabel('cost')
plt.axis([0, set_size, 0, 10])

some for:
    ...
    update_line(cost_plot, [iter, cost])
    plt.draw()
    plt.pause(0.001)

And with this code I'm plotting my cost function of my first neural network:

Graph of cost fun (network's still dead)

Now I want to do the same but for set of synapses, so I want multiple plots in one figure, updated dynamically by

update_line(plot, [iter, set of next values])

but I can't really find a way of doing this.

My data is stored in numpy's array

Final result would look something like this

Edit: Final result after doing it correctly

4
  • Have multiple calls to update_line and pass in the correct line and data? Commented May 3, 2018 at 10:23
  • What are plot and set of next values? Commented May 3, 2018 at 10:43
  • plot is line data object returned by plt.plot - it's cost_plot in working example. Set of next values is an array of values I want to plot, set of next values[0] - next value of first plot, set of next values[1], next value of second plot and so on. Commented May 3, 2018 at 10:50
  • It works with DavidG's advice, I will post solution in a moment Commented May 3, 2018 at 10:56

1 Answer 1

1

You probably want something like this :

import numpy as np
import matplotlib.pyplot as plt

def update_line(hl, i, new_data):
    hl.set_data(np.arange(i+1), new_data[:i+1])

n_data = 2
n_iter = 10
data = np.random.rand(n_data, n_iter)

plt.figure()
plt.xlabel("iter")
plt.ylabel("cost")
plt.axis([0, n_iter, 0, 1])

cost_plots = []
for i in range(n_data):
    cost_plot, = plt.plot([], [])
    cost_plots.append(cost_plot)

for i in range(n_iter):
    for j, cost_plot in enumerate(cost_plots):
        update_line(cost_plot, i, data[j])
    plt.draw()
    plt.pause(0.1)

I created a list of cost_plots and pass it to your function update_line. At each iteration, I loop over and update the different plots, and update the figure at the end of the iteration.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's almost exactly what I did just now and it's correct solution. I didn't understand what exactly plt.plot returns and I wanted somehow to place all my plot data in one Line2D object. When you make a list just like you did you can update everyone correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.