如何使用 Python 制作随时间变化的散点图动画 [英] How to Animate Scatter Plot over Time Using Python

查看:392
本文介绍了如何使用 Python 制作随时间变化的散点图动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Time    M1  M2  M3  M4  M5
1       1   2   3   1   2
2       1   3   3   1   2
3       1   3   2   1   3
4       2   2   3   1   2
5       3   3   3   1   3
6       2   3   4   1   4
7       2   3   4   3   3
8       3   4   4   3   4
9       4   4   5   3   3
10      4   4   5   5   4

上图是10个时间段的数据表.每次都有 5 个指标.如何使用 Python 随时间(10 个时间段)制作动画散点(气泡)图?

Above is a data table with 10 periods of time. For each time, there are 5 metrics. How to make an animated scatter (bubble) chart over time (10 time periods) using Python?

请注意,x轴是固定的 list = [1、2、3、4、5] ,y轴是5个元素的列表,即 time 1,y = [1, 2, 3, 1, 2];时间 2, y=[1, 3, 3, 1, 2].

Please note, x-axis is fixed list = [1, 2, 3, 4, 5] and y-axis is list of 5 elements i.e. time 1, y=[1, 2, 3, 1, 2]; time 2, y=[1, 3, 3, 1, 2].

推荐答案

您的代码中有太多错误,我无法一一列出.但以下工作.

There are just so many errors in your code, I can't list them all. But the following works.

import matplotlib.pyplot as plt
from matplotlib import animation as animation
import numpy as np
import pandas as pd
import io

u = u"""Time    M1  M2  M3  M4  M5
1       1   2   3   1   2
2       1   3   3   1   2
3       1   3   2   1   3
4       2   2   3   1   2
5       3   3   3   1   3
6       2   3   4   1   4
7       2   3   4   3   3
8       3   4   4   3   4
9       4   4   5   3   3
10      4   4   5   5   4"""

df_Bubble = pd.read_csv(io.StringIO(u), delim_whitespace=True)

time_count = len(df_Bubble) 
colors = np.arange(1, 6) 
x = np.arange(1, 6) 
max_radius = 25 
fig, ax = plt.subplots() 
pic = ax.scatter(x, df_Bubble.iloc[0, 1:], s=100, c=colors) 
pic.set_offsets([[np.nan]*len(colors)]*2)
ax.axis([0,7,0,7])

def init(): 
    pic.set_offsets([[np.nan]*len(colors)]*2)
    return pic,

def updateData(i): 
    y = df_Bubble.iloc[i, 1:] 
    area = np.pi * (max_radius * y / 10.0) ** 2 
    pic.set_offsets([x, y.values]) 
    pic._sizes = area
    i+=1 
    return pic, 

ani = animation.FuncAnimation(fig, updateData, frames=10, interval = 50, blit=True, init_func=init) 

plt.show()

这篇关于如何使用 Python 制作随时间变化的散点图动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆