最近回顧學習排序,想用python實現,考慮可視化github上有一個python得https://github.com/ZQPei/Sorting_Visualization
還不錯。
不過有用到opencv、pygame,我不太想用這個,看是否能直接用matplotlib畫,有兩種思路:①animation動畫思路、②自己手動draw。
這一篇是自己探索的第②種,自己手動draw得方式
注意點:
①ipython中無法動態實時更新,python console中纔可以,使過一直都是空白,等代碼全都執行完畢,纔會顯示最後得一張圖,坑掉我無數實踐
②實時動態,使用plt.pause(seconds)方式非阻塞刷新draw;(資料說需要開啓交互方式plt.ion() 用完需關閉plt.ioff(),但測試並不是)
③最後可用plt.show()來阻塞,防止運行玩自己關閉了。
自己draw動態更新
plt.bar柱狀圖,當排序交換數據時,將柱狀圖中的height數據進行交換,然後draw即可
源碼:(一定是python console,不是ipython,否則會生成很多得圖片輸出)
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 21 00:32:06 2019
pyplot_dynamic_draw_sample_01.py
在ipython中無法體現出動態效果,需要再window得cmd中啓動pyton(linux也是一樣console啓動),然後輸入下面得文件就能看到效果
@author: Sudaxia
"""
#matplotline #jupyter ipython中別加inline就能畫圖出來
import matplotlib.pyplot as plt
import random
#plt.ion()
plt.ioff()
def swapAndDraw(data,x1,x2):
temp1height=tempbar[x1].get_height()
tempbar[x1].set_height(tempbar[x2].get_height())
tempbar[x2].set_height(temp1height)
tempbar[x2].set_fc("red")
plt.draw()
plt.pause(0.001)
tempbar[x2].set_fc("green")#記得顏色換回來
#冒泡排序
data=random.sample(range(20),20)
print data
n=len(data)
tempbar=plt.bar(range(n),data,fc="green")
for m in range(n):#趟數
for i in range(n-m-1):
if data[i]>data[i+1]:
data[i+1],data[i]=data[i],data[i+1]
#print "data:\t",data
swapAndDraw(data,i,i+1)
#print "bar:\t",[x.get_height() for x in tempbar]
print data;
plt.ioff();
#plt.show();
效果:因爲保存爲gif又涉及到其它,我就只貼結果圖了,代碼運行就知道了
下一篇講解animation動畫排序展示,並保存文件