for a computer science project I had to implement Lloyds-Algorithm which seems to have worked pretty good. I'd like to visualize the iterations. Which also works kind of already:
import numpy
import matplotlib.pyplot as plt
# Variables to test
centroids = [[[2, 3],[6, 7]],
[[1, 2],[7, 8]]]
nearest_centroid_of_samples = [[0, 0, 1, 1, 0],
[0, 1, 1 , 1, 0]]
quant_error = [2.123,1.789]
# Actual code
i=0
for c,ncos, qe in zip(centroids, nearest_centroid_of_samples, quant_error):
# My x and y values
xx = [0, 4, 3, 8, 2]
yy = [1, 3, 9, 5, 2]
title = "Iteration Nr.%d" % (i)
plt.title(title)
# A text I would like to appear
text = "Quantisierungsfehler: %f" % (qe)
plt.text(12.5, 3.5, text)
# Adding my clusters to the plot, ncos encodes the color
plt.scatter(xx, yy, c=ncos, marker='o', alpha=1)
# Here I'm adding my centroids (the middle of each cluster) to the plot
for pos in c:
plt.scatter(pos[0], pos[1], c="red", marker="+")
i = i+1
plt.pause(0.25)
plt.show()
This basically already gives me what I want. With only one little problem: It appears to draw each iteration on top of the previous one. Which is no problem for my data, since they match up perfectly and you can't see this. But the red marks for the centroids kinda bug out and keep being visible a little bit - and worse, the text I want to add has a longer decimal number which gets unreadable.
How do I need to plot this, that it draws everything new, but still in the same figure?
Best Regards
doofesohr
Edited in some representative values as per suggestion. These do not represent a result of Lloyds-Algorithm, but should still show where my problem is/was.
Make the following changes in your code-
# to control the number of decimal places in the quantisation error
# change %f ----> %.2f for 2 decimal places or how many ever you want
text = "Quantisierungsfehler: %.2f" % (qe)
# to clear the contents of a figure and plot freshly add plt.cla() after plt.pause(0.25) i.e
plt.pause(0.25)
plt.cla()