Python可视化1-animation

animation包在matplotlib中,需要from matplotlib import animation,主要用于动画的制作,可以用来绘制运动的轨迹动画

animation主要函数(animaton.FuncAnimation)

animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
    -fig:Figure对象,确定动画所在图
    -func:创建每一帧图像的函数,更新轨迹动画的函数
    -frames:定义一个动画帧的序列,确定动画运行的帧数,可以作为参数传递至func中用于更新轨迹
    -init_func:绘制初始图像界面,主要确定坐标区间范围

    -interval:每隔多长时间显示一帧画面

    -repeat:是否重复动画

func参数

传入frames用于更新轨迹的坐标数据

提前定义x_data,y_data列表用于存储轨迹

使用frames,利用append函数计算更新x_data,y_data(或者是从构建好的轨迹列表中作为索引取出相应的坐标)

轨迹line

plt.plot()将返回图线对象

line, = plt.plot(),这里使用line加逗号解包,因为返回值不只图线对象

在func函数中更新或取出x_data,y_data中的值后,使用line.set_data(x_data,y_data)更新图线对象,最后func函数返回line对象

frames

frames确定帧数,可以使用np.linspace()函数或range()函数定义

init_func()

用于确定初始动画图像范围的函数,使用plt.subplots()可以返回figure对象以及axis对象。

使用其中的axis对象,设置动画的显示范围ax.set_xlim(),ax.set_ylim()

ani.save(文件名/路径)

该函数最后可以用来保存动画,可以保存为mp4格式/gif文件(此处的ani为使用animation.FuncAnimation()返回的动画对象)

ani.save('ani_1.mp4', writer='ffmpeg')

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Python 的 tkinter 模块来实现可视化界面,使用 matplotlib 库来绘制排序过程中的图形。 以下是一个示例代码,实现了十大排序算法的可视化界面: ```python import random import time import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import tkinter as tk class SortingVisualization: def __init__(self, sort_algorithm, length=100): self.length = length self.data = [i+1 for i in range(length)] random.shuffle(self.data) self.sort_algorithm = sort_algorithm(self.data) self.fig, self.ax = plt.subplots() self.ax.set_title(self.sort_algorithm.__class__.__name__) self.bar_rects = self.ax.bar(range(len(self.data)), self.data, align="edge") self.ax.set_xlim(0, len(self.data)) self.ax.set_ylim(0, int(1.07 * length)) self.iteration = self.sort_algorithm.sort() self.start_time = time.time() def update(self, rects, iteration): for rect, val in zip(rects, self.data): rect.set_height(val) try: next(self.iteration) except StopIteration: self.ax.set_title(f"{self.sort_algorithm.__class__.__name__} ({time.time()-self.start_time:.2f}s)") return False return True def animate(self, i): return self.update(self.bar_rects, i) def start(self): anim = FuncAnimation(self.fig, self.animate, frames=range(len(self.data)), interval=1, repeat=False, blit=True) plt.show() class BubbleSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) for i in range(n): for j in range(n-i-1): if self.data[j] > self.data[j+1]: self.data[j], self.data[j+1] = self.data[j+1], self.data[j] yield class SelectionSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) for i in range(n): min_idx = i for j in range(i+1, n): if self.data[min_idx] > self.data[j]: min_idx = j self.data[i], self.data[min_idx] = self.data[min_idx], self.data[i] yield class InsertionSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) for i in range(1, n): key = self.data[i] j = i - 1 while j >= 0 and key < self.data[j]: self.data[j+1] = self.data[j] j -= 1 yield self.data[j+1] = key yield class QuickSort: def __init__(self, data): self.data = data def sort(self): def _quick_sort(l, r): if l < r: p = self.partition(l, r) yield from _quick_sort(l, p-1) yield from _quick_sort(p+1, r) yield from _quick_sort(0, len(self.data)-1) def partition(self, l, r): pivot = self.data[r] i = l - 1 for j in range(l, r): if self.data[j] < pivot: i += 1 self.data[i], self.data[j] = self.data[j], self.data[i] yield self.data[i+1], self.data[r] = self.data[r], self.data[i+1] yield return i + 1 class MergeSort: def __init__(self, data): self.data = data def sort(self): def _merge_sort(l, r): if l < r: m = (l + r) // 2 yield from _merge_sort(l, m) yield from _merge_sort(m+1, r) yield from self.merge(l, m, r) yield from _merge_sort(0, len(self.data)-1) def merge(self, l, m, r): L = self.data[l:m+1] R = self.data[m+1:r+1] i = j = 0 k = l while i < len(L) and j < len(R): if L[i] < R[j]: self.data[k] = L[i] i += 1 else: self.data[k] = R[j] j += 1 k += 1 yield while i < len(L): self.data[k] = L[i] i += 1 k += 1 yield while j < len(R): self.data[k] = R[j] j += 1 k += 1 yield class HeapSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) for i in range(n // 2 - 1, -1, -1): yield from self.heapify(n, i) for i in range(n-1, 0, -1): self.data[0], self.data[i] = self.data[i], self.data[0] yield yield from self.heapify(i, 0) def heapify(self, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and self.data[largest] < self.data[l]: largest = l if r < n and self.data[largest] < self.data[r]: largest = r if largest != i: self.data[i], self.data[largest] = self.data[largest], self.data[i] yield yield from self.heapify(n, largest) class ShellSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) gap = n // 2 while gap > 0: for i in range(gap, n): temp = self.data[i] j = i while j >= gap and self.data[j-gap] > temp: self.data[j] = self.data[j-gap] j -= gap yield self.data[j] = temp yield gap //= 2 class CountingSort: def __init__(self, data): self.data = data def sort(self): n = len(self.data) output = [0] * n count = [0] * (max(self.data) + 1) for i in range(n): count[self.data[i]] += 1 for i in range(1, len(count)): count[i] += count[i-1] for i in range(n-1, -1, -1): output[count[self.data[i]]-1] = self.data[i] count[self.data[i]] -= 1 yield self.data = output class RadixSort: def __init__(self, data): self.data = data def sort(self): def _counting_sort(exp): n = len(self.data) output = [0] * n count = [0] * 10 for i in range(n): idx = (self.data[i] // exp) % 10 count[idx] += 1 for i in range(1, len(count)): count[i] += count[i-1] for i in range(n-1, -1, -1): idx = (self.data[i] // exp) % 10 output[count[idx]-1] = self.data[i] count[idx] -= 1 yield self.data = output max_val = max(self.data) exp = 1 while max_val // exp > 0: yield from _counting_sort(exp) exp *= 10 class GUI: def __init__(self): self.window = tk.Tk() self.window.title("Sorting Visualization") self.window.geometry("320x240") self.sorts = {"Bubble Sort": BubbleSort, "Selection Sort": SelectionSort, "Insertion Sort": InsertionSort, "Quick Sort": QuickSort, "Merge Sort": MergeSort, "Heap Sort": HeapSort, "Shell Sort": ShellSort, "Counting Sort": CountingSort, "Radix Sort": RadixSort} self.sort_var = tk.StringVar(self.window, sorted(self.sorts.keys())[0]) sort_menu = tk.OptionMenu(self.window, self.sort_var, *self.sorts.keys()) sort_menu.pack(pady=10) length_var = tk.StringVar(self.window, "100") length_entry = tk.Entry(self.window, textvariable=length_var) length_entry.pack(pady=5) start_button = tk.Button(self.window, text="Start", command=self.start) start_button.pack(pady=10) self.window.mainloop() def start(self): try: length = int(length_var.get()) sort_algorithm = self.sorts[self.sort_var.get()] SortingVisualization(sort_algorithm, length).start() except ValueError: return if __name__ == "__main__": GUI() ``` 运行该代码,会弹出一个 GUI 界面,选择排序算法和数据长度后,点击 Start 按钮即可开始可视化排序过程。 注意:由于排序算法的实现方式不同,排序时间也会有所不同,因此排序过程中的动画时间也会有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值