前言
前几天学习了下 Matplotlib,数据分析的事情暂告一段落, 就琢磨用它来搞点事情。
正好前几天有个逻辑里写了个快排,今天有时间就想着用 Matplotlib 来绘制排序过程,炒鸡好用啊。
一、图表展示冒泡排序
对下面的列表进行排序:
l = [5, 23, 43, 95, 62, 76, 34]
排序过程图示:
非常直观有没有,其他的排序过程绘制也就简单了。对初学者非常友好。。有木有:》
图表源码
#!/usr/bin/python3
import print_help as p
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
count = 0
fig = plt.figure()
# 图形绘制函数
def draw1(l, v):
global count
global fig
if count > 0 and count % 8 == 0:
fig = plt.figure()
count = 0
ax1 = fig.add_subplot(4, 2, count+1)
# 绘制坐标轴
ax1.axis([0, len(l) + 1, 1, 110])
xmajorLocator = MultipleLocator(1)
ymajorLocator = MultipleLocator(20)
ax1.xaxis.set_major_locator(xmajorLocator)
ax1.yaxis.set_major_locator(ymajorLocator)
# 绘制列表柱状图
x = [x + 1 for x in range(len(l))]
bar = plt.bar(x, l)
# 绘制数值
for a, b in zip(x, l):
plt.text(a, b+0.05, '%.0f' % b, ha='center', va='bottom', fontsize=11)
# 绘制当前移动的数
for ba, y in zip(bar, l):
if y == v:
ba.set(color="red")
count += 1
# 冒泡排序
# 从最后一个开始, 将最小的元素上浮到前端有序队列
def sort(l):
for i in range(0, len(l)):
change = False
for j in range(len(l)-1, i, -1):
draw1(l, l[j])
if l[j] < l[j-1]:
l[j], l[j-1] = l[j - 1], l[j]
change = True
if not change:
print("return")
return
l = [5, 23, 43, 95, 62, 76, 34]
sort(l)
plt.show()
二、动画展示冒泡排序
动画源码
#!/usr/bin/python3
import print_help as p
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from IPython.display import display, clear_output
count = 0
fig, ax1 = plt.subplots()
# 图形绘制函数
def draw1(l, v):
global count
global fig
global ax1
ax1.cla()
# 绘制坐标轴
ax1.axis([0, len(l) + 1, 1, 110])
xmajorLocator = MultipleLocator(1)
ymajorLocator = MultipleLocator(20)
ax1.xaxis.set_major_locator(xmajorLocator)
ax1.yaxis.set_major_locator(ymajorLocator)
# 绘制列表柱状图
x = [x + 1 for x in range(len(l))]
bar = plt.bar(x, l)
# 绘制数值
for a, b in zip(x, l):
plt.text(a, b+0.05, '%.0f' % b, ha='center', va='bottom', fontsize=11)
# 绘制当前移动的数
for ba, y in zip(bar, l):
if y == v:
ba.set(color="red")
plt.pause(0.5)
clear_output(wait = True)
display(fig)
clear_output(wait = True)
plt.pause(0.01)
count += 1
# 冒泡排序
# 从最后一个开始, 将最小的元素上浮到前端有序队列
def sort(l):
for i in range(0, len(l)):
change = False
for j in range(len(l)-1, i, -1):
draw1(l, l[j])
if l[j] < l[j-1]:
l[j], l[j-1] = l[j - 1], l[j]
change = True
if not change:
print("return")
return
l = [5, 23, 43, 95, 62, 76, 34]
plt.pause(3)
sort(l)
plt.show()