我一直在用 Python 制作一個基于“排序之聲”的排序可視化工具。我遇到了問題。我無法在排序程序中運行 matplotlib 繪圖并更新它,并且我希望該繪圖具有影片效果。顯而易見的解決方案是異步或多執行緒,但我無法讓它作業。我想不出解決辦法,只好求助。這是代碼:
from random import randint
from timeit import repeat
from matplotlib import animation
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import time
import numpy as np
import os
import asyncio
def bubble_sort(array):
n = len(array)
global arrayGlobal
for i in range(n):
already_sorted = True
for j in range(n - i - 1):
if array[j] > array[j 1]:
array[j], array[j 1] = array[j 1], array[j]
already_sorted = False
if already_sorted:
break
arrayGlobal = array
time.sleep(0.1)
print(arrayGlobal)
return array
def visTest():
reshaped = np.reshape(arrayGlobal, (5, 5))
fig = plt.figure()
def animate(i):
sns.heatmap(reshaped, cbar=False)
anim = animation.FuncAnimation(fig, animate)
plt.show()
ARRAY_LENGTH = 25
array = [randint(0, 100) for i in range(ARRAY_LENGTH)]
async def start():
loop = asyncio.get_running_loop()
await asyncio.gather(loop.run_in_executor(None, bubble_sort, (array)), loop.run_in_executor(None, visTest))
asyncio.run(start())
先感謝您。
uj5u.com熱心網友回復:
根據您運行 Python 的方式,您可以使用plt.pause(0.01)來顯示中間圖。asyncio不需要(您沒有對數百萬個數字進行排序)。
這是一個示例(在互動式 PyCharm 環境中測驗)。
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
def bubble_sort(array):
n = len(array)
for i in range(n):
already_sorted = True
for j in range(n - i - 1):
if array[j] > array[j 1]:
array[j], array[j 1] = array[j 1], array[j]
already_sorted = False
# sns.heatmap(np.reshape(array, (5, 5)), cbar=False, ax=ax)
ax.cla()
sns.barplot(x=np.arange(n), y=array,
hue=(np.arange(n) == j 1) 2 * (np.arange(n) > n - i - 1),
dodge=False, palette=['turquoise', 'crimson', 'deepskyblue'], ax=ax)
ax.legend_.remove()
ax.set_xticks([])
plt.pause(0.1)
plt.pause(1)
if already_sorted:
break
return array
fig, ax = plt.subplots()
array = np.random.uniform(2, 100, 10)
bubble_sort(array)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394398.html
標籤:Python 排序 matplotlib
