0

You have specific data points in my program that remains the same. I am trying to fit a line with through data by doing iterated updates. I want to see how the line changes (moves) while updating parameters for this line.

In specific I am doing gradient descent and I am trying to see how each update changes the angle and position of the line to best fit the data.

Right now I got this:

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
plt.show()

Which results in something like this: enter image description here

As you can see I also have a hard time of plotting a continuous line. Now I need to update the red line. Any ideas? thetas[0] and thetas[1] are updates in a for loop after which the plot needs to be updated as well..

2 Answers 2

5

You need to use matplotlib's interactive mode (see documentation).

Especially, you need to use plt.ion() to turn the interactive mode on, fig.canvas.draw() to update the canvas with the latest changes, and ax.clear() to remove what has been plotted before.

Your code would look like:

plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Draw.
fig.canvas.draw()

# Do your updates on thetas.
# ...

# Clear the current plot.
ax1.clear()
# Plot your data again.
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Update the figure.
fig.canvas.draw()
Sign up to request clarification or add additional context in comments.

Comments

1

Seems like you are looking for an animation. You need to rearrange your code so you can use matplotlib.animation.FuncAnimation.

This is a basic example: http://matplotlib.org/examples/animation/animate_decay.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.