每个数据点具有不同颜色的动画图 [英] Animated plot with different color for every data point

查看:57
本文介绍了每个数据点具有不同颜色的动画图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个时间序列的动画图,但我希望能够以不同的方式为每个数据点着色.在对时间数据执行各种分析任务时,我也想根据每个数据点所属的区域为它们着色.

I want to create an animated plot of a timeserie but I want to be able to color every data point differently. While I am running various analysis tasks on the timeserie data I want to color each data point according to the region that it belongs too.

我遵循了这个示例,以了解动画绘图的工作原理,我还发现答案展示了颜色如何可以纳入.问题在于,在这种方法中,每次迭代都会重新绘制整个图,从而改变整个图的颜色,而不仅仅是新绘制的数据点.

I followed this example to get an understanding of how animated plotting works and I also found that answer that showcases how color can be incorporated. The problem is that in that approach the whole graph is re-plotted in every iteration, thus changing the color of the whole graph and not the newly plotted data point only.

有人可以告诉我如何更改衰减示例以为每个数据点分配不同的颜色吗?

Can someone show me how the decay example can be altered to assign different color to each data point?

推荐答案

您可以使用 scatter 为点着色,并且您不打算绘制过多的点,只需每次添加新点即可.不同的颜色可能是要走的路.基于衰减的最小示例,

You can colour points using scatter and provided you're not planning on plotting too many points, simply adding new points each time with different colours may be the way to go. A minimal example based on decay,

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


def data_gen(t=0):
    cnt = 0
    while cnt < 1000:
        cnt += 1
        t += 0.01
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)

def get_colour(t):
    cmap = matplotlib.cm.get_cmap('Spectral')
    return cmap(t%1.)

def init():
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 10)


fig, ax = plt.subplots()
ax.grid()

def run(data):

    # Get some data and plot
    t, y = data
    ax.scatter(t, y, c=get_colour(t))

    #Update axis
    xmin, xmax = ax.get_xlim()
    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()

ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
                              repeat=False, init_func=init)
plt.show()

这篇关于每个数据点具有不同颜色的动画图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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