to plot the graph on same image in multiple iterations in python

Viewed 34
from sklearn.datasets import make_blobs
from matplotlib import pyplot
from pandas import DataFrame
# generate 2d classification dataset
X, y = make_blobs(n_samples=30, centers=2, n_features=2)
# scatter plot, dots colored by class value
df = DataFrame(dict(x=X[:,0], y=X[:,1], label=y))
colors = {0:'red', 1:'blue'}
fig, ax = pyplot.subplots()
grouped = df.groupby('label')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=colors[key])
pyplot.show()

import numpy as np
import time
import matplotlib.pyplot as plt
import math
MAT= df.to_numpy()
Iterate = len(MAT)
w0=1.0;w1=1.0;w2=2.0
change = True
#plt.ion()
while change == True:
  change = False
  for i in range(Iterate):
    arr=MAT[i:]
    if (arr[0][2]==1.0 and (w0+w1*arr[0][0]+w2*arr[0][1] < 0.0)):
      w0=w0 + 1.0;w1=w1+arr[0][0];w2=w2+arr[0][1]
      change = True
    if (arr[0][2]==0.0 and (w0+w1*arr[0][0]+w2*arr[0][1] >= 0.0)):
      w0=w0 - 1.0;w1=w1-arr[0][0];w2=w2-arr[0][1]
      change = True
    Intecept=-w0/w2;Slope=-w1/w2
    df = DataFrame(dict(x=X[:,0], y=X[:,1], label=y))
    X1=(X[:,0])
    Y1= (X[:,1])
    low1 = math.floor(min(X1))
    high1 = math.ceil(max(X1))
    low2 = math.floor(min(Y1))
    high2 = math.ceil(max(Y1))
    colors = {0:'red', 1:'blue'}
    fig, ax = pyplot.subplots()
    grouped = df.groupby('label')
    for key, group in grouped:
        group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=colors[key])
    plt.xlim(low1, high1), plt.ylim(low2,high2)
    axes = plt.gca()
    x_vals = np.array(axes.get_xlim())
    y_vals = Intecept + Slope * x_vals
    plt.plot(x_vals, y_vals, '--')
    plt.xlabel('x')
    plt.ylabel('y')
    pyplot.draw()
    time.sleep(0.05)
    plt.show()

I am sharing a python code which is doing binary classification and the result is shown on a graph but i want the changes on a single image. It is basically perceptron classifier. In while loop I am putting my scattered graph and then plotting my line in it.

1 Answers

Momentarely a new figure gets created in the loop every time with fig, ax = pyplot.subplots(). Additionally, at the end of the loop, the code gets halted via plt.show().

You could achieve the desired behaviour by putting fig, ax = pyplot.subplots() outside of the while loop, replacing time.sleep(0.05) and plt.show() by plt.show(pause=False) and plt.pause(0.05) and adding a plt.show() after the loop too keep showing the figure after having left the loop.

Pseudo code:

fig, ax = pyplot.subplots()
while keep_looping:
  for i in iterator:
    if criteria:
      keep_looping = False
    plt.plot(data)
    plt.show(block=False)
    plt.pause(0.05)
plt.show()
Related