动画散点图,每个点具有不同的颜色和大小

时间:2020-02-18 22:01:54

标签: python matplotlib animation

我有一个脚本生成的实时数据,该脚本生成x,y1,y2值,其中x是连续的,
-10

我需要在散点图中显示y1,y2值,在散点图中,我只能看到最后3个输入。我还想使用FuncAnimation实时更新此图。

想法是看到屏幕上的3个点,每个值都应按日期识别。 最后一个(i)可以是红色和大号,(i-1)黄色和中号,(i-2)绿色和小号。

data_gen.py:


import csv
import random
import time
X = 0
Y = 0
Y2 = 0
fieldnames = ["X", "Y", "Y2"]

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

while True:
    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        info = {
            "X": X,
            "Y": Y,
            "Y2": Y2
        }

        csv_writer.writerow(info)
        print(X, Y, Y2)

        X += 1
        Y = random.randint(-10, 10)
        Y2 = random.randint(-10, 10)
    time.sleep(1)

Test.py:

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

def main():

    numframes = 100
    numpoints = 10
    color_data = np.random.random((numframes, numpoints))
    plt.style.use('fivethirtyeight')
    data = pd.read_csv('data.csv')
    x,y1,y2 = data['X'],data['Y'], data['Y2']

    y1 = y1[-3:]
    y2 = y2[-3:]
    x_ = x.to_numpy()
    y1_ = y1.to_numpy()
    y2_ = y2.to_numpy()
    y1_ = y1_.reshape(-1, 1)
    y2_ = y2_.reshape(-1, 1)
    y_tot= np.hstack((y1_,y2_))

    fig = plt.figure()
    scat = plt.scatter(y1_, y2_,color='red')

    axes = plt.gca()
    axes.set_xlim(-14, 14)
    axes.set_ylim(-14,14)

    ani = animation.FuncAnimation(fig, update_plot,interval=1000, frames=range(numframes),fargs=(color_data, scat))
    plt.show()

def update_plot(i, data, scat):
    data = pd.read_csv('data.csv')
    x,y1,y2 = data['X'],data['Y'], data['Y2']
    y1 = y1[-3:]
    y2 = y2[-3:]

    x_ = x.to_numpy()
    y1_ = y1.to_numpy()
    y2_ = y2.to_numpy()
    y1_ = y1_.reshape(-1, 1)
    y2_ = y2_.reshape(-1, 1)
    y_tot= np.hstack((y1_,y2_))


    '''Set de values'''
    scat.set_offsets(y_tot)
    '''Set de color'''
    # scat.set_array(data[i])
    '''Set de tamaño'''
    # scat.set_sizes(scat.get_sizes()*2)
    return scat,

main()

我不知道如何进行。像现在一样,我可以显示.csv中生成的最后3个更新值,但是我不能确定哪个是最后一个。

我应该做类似的事情

plt.plot(y1_[0],y2_[0],'r',y1_[1],y2_[1],'y',y1_[2],y2_[2],'g')

在“动画”功能内部?

谢谢!

0 个答案:

没有答案