【问题标题】:Animating data sorting in python在python中动画数据排序
【发布时间】:2022-01-18 12:56:27
【问题描述】:

我试图开发一个程序,将 python 中列表的排序可视化为散点图,但我不知道从哪里开始。谷歌搜索后,我想出了以下代码,它做同样的事情,但在条形图上:

# import all the modules
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mp
import numpy as np
import random
  
# set the style of the graph
plt.style.use('fivethirtyeight')
  
# input the size of the array (list here)
# and shuffle the elements to create
# a random list
n = int(input("enter array size\n"))
a = [i for i in range(1, n+1)]
random.shuffle(a)
  
# insertion sort
  
  
def insertionsort(a):
    for j in range(1, len(a)):
        key = a[j]
        i = j-1
  
        while(i >= 0 and a[i] > key):
            a[i+1] = a[i]
            i -= 1
  
            # yield the current position
            # of elements in a
            yield a
        a[i+1] = key
        yield a
  
  
# generator object returned by the function
generator = insertionsort(a)
  
# to set the colors of the bars.
data_normalizer = mp.colors.Normalize()
color_map = mp.colors.LinearSegmentedColormap(
    "my_map",
    {
        "red": [(0, 1.0, 1.0),
                (1.0, .5, .5)],
        "green": [(0, 0.5, 0.5),
                  (1.0, 0, 0)],
        "blue": [(0, 0.50, 0.5),
                 (1.0, 0, 0)]
    }
)
  
  
fig, ax = plt.subplots()
  
# the bar container
rects = ax.bar(range(len(a)), a, align="edge",
               color=color_map(data_normalizer(range(n))))
  
# setting the view limit of x and y axes
ax.set_xlim(0, len(a))
ax.set_ylim(0, int(1.1*len(a)))
  
# the text to be shown on the upper left
# indicating the number of iterations
# transform indicates the position with
# relevance to the axes coordinates.
text = ax.text(0.01, 0.95, "", transform=ax.transAxes)
iteration = [0]
  
# function to be called repeatedly to animate
  
  
def animate(A, rects, iteration):
  
    # setting the size of each bar equal
    # to the value of the elements
    for rect, val in zip(rects, A):
        rect.set_height(val)
  
    iteration[0] += 1
    text.set_text("iterations : {}".format(iteration[0]))
  
  
anim = FuncAnimation(fig, func=animate,
                     fargs=(rects, iteration), frames=generator, interval=50,
                     repeat=False)
  
plt.show()

有没有人可以给我关于如何将其转换为散点图的建议? (尤其是def animate 部分,我应该如何更新散点图的值?)我尝试阅读文档,但它似乎没有给我所需的帮助,如果有人能指出我,我将不胜感激方向正确。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

执行此操作的一种方法是简单地删除定义条形图rects = ax.bar(range(len(a)), a, align="edge",color=color_map(data_normalizer(range(n)))) 的线,而改为声明散点图dots=ax.scatter(range(len(a)),a,color=color_map(data_normalizer(range(n))))。正如您所注意到的,更新散点图与更新条形图略有不同。我采用的方法是使用set_offsets 来更新散点图上的点(条形图的等价物是set_height)。您可以通过 cmets 中提供的链接 r-beginners 找到有关此内容的更多详细信息以及更新散点图和创建散点图动画的更多方法。

整体代码如下:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mp
import numpy as np
import random

plt.style.use('fivethirtyeight')

n = int(input("enter array size\n"))
a = [i for i in range(1, n+1)]
random.shuffle(a)
  
def insertionsort(a):
    for j in range(1, len(a)):
        key = a[j]
        i = j-1
  
        while(i >= 0 and a[i] > key):
            a[i+1] = a[i]
            i -= 1
            yield a
        a[i+1] = key
        yield a
  
generator = insertionsort(a)
data_normalizer = mp.colors.Normalize()
color_map = mp.colors.LinearSegmentedColormap(
    "my_map",
    {
        "red": [(0, 1.0, 1.0),
                (1.0, .5, .5)],
        "green": [(0, 0.5, 0.5),
                  (1.0, 0, 0)],
        "blue": [(0, 0.50, 0.5),
                 (1.0, 0, 0)]
    }
)
  
fig, ax = plt.subplots()
  
dots=ax.scatter(range(len(a)),a,color=color_map(data_normalizer(range(n))))
ax.set_xlim(0, len(a))
ax.set_ylim(0, int(1.1*len(a)))
  
text = ax.text(0.01, 0.95, "", transform=ax.transAxes)
iteration = [0]

def animate(A,dots,iteration):

    up_points=np.array([np.arange(len(a)),np.array(A)]).T
    dots.set_offsets(up_points)
    iteration[0] += 1
    text.set_text("iterations : {}".format(iteration[0]))
    
anim=FuncAnimation(fig,func=animate,fargs=(dots,iteration,),frames=generator,interval=30,repeat=True)
plt.show()

30 fps 的 25 点输出给出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2013-03-03
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多