visualize_1.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import sys
  2. import time
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from matplotlib.animation import FuncAnimation
  6. class Plotter:
  7. # initialising all the raw data and additional kwarg for animation function
  8. def __init__(self, arr, interval=1, title="Bubble Sort", *,
  9. repeat=0, window_shape=(7,5), xkcd=0):
  10. self.is_xkcd = xkcd
  11. self.arr = arr
  12. self.title = title
  13. self.window_shape = window_shape
  14. self.interval = interval
  15. self.repeat = repeat
  16. self.x = np.arange(start=0, stop=arr.shape[1]) # getting size of arr
  17. @staticmethod
  18. def on_close(event):
  19. if not sys.argv[0] == 'test.py':
  20. sys.exit(0)
  21. def animate(self, at):
  22. [self.bar_collections[i].set_height(self.arr[at][i]) for i in range(len(self.bar_collections))]
  23. # self.fig.canvas.draw() # forces canavas to draw a frame
  24. def plot_util(self):
  25. self.fig, self.graph = plt.subplots(figsize=self.window_shape)
  26. self.fig.canvas.mpl_connect('close_event', self.on_close)
  27. self.graph.yaxis.set_visible(False)
  28. self.graph.xaxis.set_visible(False)
  29. self.graph.text(0, 1.15, self.title, transform=self.graph.transAxes,
  30. size=24, weight=300, ha='left', va='top')
  31. self.bar_collections = self.graph.bar(self.x, self.arr[0], align='edge', width=0.5)
  32. # since the animate method in not returning any thing, thus we are using blit=False
  33. anim = FuncAnimation(self.fig, self.animate, frames=self.arr.shape[0],
  34. interval=self.interval, blit=0, repeat=self.repeat,
  35. repeat_delay=1000)
  36. plt.box(False)
  37. time.sleep(1)
  38. plt.show()
  39. anim.event_source.stop()
  40. del anim
  41. plt.close()
  42. def plot(self):
  43. try:
  44. if self.is_xkcd:
  45. with plt.xkcd():
  46. self.plot_util()
  47. else:
  48. self.plot_util()
  49. except: pass