【问题标题】:How to create a video that plots the scatter plots one by one using python?如何使用python创建一个一张一张地绘制散点图的视频?
【发布时间】:2021-07-02 08:20:08
【问题描述】:

我正在将一些数据绘制为散点图,这些散点图覆盖在图像上。我想通过一次绘制一个散点来制作动画。这是我现在使用和编辑来自here 的答案的代码:

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

x = random.sample(range(0, 287), 20)
y = random.sample(range(0, 380), 20)
size =  [20 for x in range(20)]
colors = ["r" for x in range(20)]


cm = plt.get_cmap('jet')

fig = plt.figure(figsize=(18,9))

graph = plt.scatter([], [],marker='+')
url = 'https://raw.githubusercontent.com/kornelski/pngquant/master/test/img/test.png'
im = plt.imread(url)
def animate(i):
        
    implot = plt.imshow(im)
    graph.set_offsets(np.vstack((x[:i+1], y[:i+1])).T)
    graph.set_sizes(size[:i])
    graph.set_facecolors(colors[:i+1])
    return graph

ani = FuncAnimation(fig, animate, repeat=False, interval=0.1)
plt.show()

有两件事我需要帮助。

  1. 我希望散点图的颜色根据第三个变量而改变,即使用cmap。但是,set_facecolors 不接受这样的论点。
  2. 当我尝试使用 ani.save('files/animation.gif',writer='imagemagick', fps=60) 保存动画时,我的 jupyter 笔记本崩溃了。

有人可以帮我吗?

【问题讨论】:

    标签: python matplotlib matplotlib-animation


    【解决方案1】:

    图形的背景图是通过添加ax来绘制的。颜色图也根据数据的数量,20个创建,并创建一个列表,以便可以显示每种颜色。由于图像的坐标和图形的坐标基础不同,所以y轴设置为相反的方向。

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    import random
    from PIL import Image
    import urllib.request
    
    random.seed(20210702)
    N = 20
    x = random.sample(range(0, 380), N)
    y = random.sample(range(0, 287), N)
    size =  [20 for x in range(N)]
    colors = []
    
    cm = plt.get_cmap('jet', N)
    
    fig,ax = plt.subplots(figsize=(9, 4.5))
    plt.xlim(0, 380)
    plt.ylim(287, 0)
    graph = ax.scatter([], [], marker='+')# 
    
    url = 'https://raw.githubusercontent.com/kornelski/pngquant/master/test/img/test.png'
    im = Image.open(urllib.request.urlopen(url))
    print(im.size)
    
    def animate(i):
        ax.imshow(im)
        graph.set_offsets(np.vstack((x[:i+1], y[:i+1])).T)
        graph.set_sizes(size[:i+1])
        colors.append(cm(i))
        graph.set_facecolors(colors) 
        return graph
    
    ani = FuncAnimation(fig, animate, frames=20, repeat=False, interval=200)
    plt.show()
    

    【讨论】:

    • 这很好用,谢谢。对于size 数组,我理解它应该是帧数的大小是否正确?
    • 是的,没错。您可以通过更改 size 数组的值来更改标记的大小。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多