在Matplotlib动画中绘制具有不同颜色的数据点

3

我有这段代码:

fig,ax=subplots(figsize=(20,10))

#ax=plot(matriz[0],matriz[1],color='black',lw=0,marker='+',markersize=10)
#ax=plot(matriz[2],matriz[3],color='blue',lw=0,marker='o',markersize=10)
#show ()
def animate(i):
    ax=plot((matt[i][0],matt[i][2]),(matt[i][1],matt[i][3]),lw=0,color='r-',marker='o',markersize=8)
    return ax

anim=animation.FuncAnimation(fig,animate,frames=numlin, interval=1000,blit=True,repeat=0)
show()

我在matplotlib方面没有经验,但我的老板要求我在每次迭代中用不同的颜色给每个点着色(例如,点1用红色,点2用蓝色等)。我想使用不同的颜色给每个点着色,但在下一次迭代中应该保持相同的颜色。

在matplotlib中如何实现这个功能?


4
请查看http://matplotlib.org/examples/pylab_examples/scatter_demo2.html。每个点实际上都有一个(x,y,size,color)元组,尽管实际的函数参数是x值向量,y值向量,大小向量和颜色向量等。 - cphlewis
@cphlewis 我能看到这个例子,但我不明白哪一行代码为每个点添加了颜色。使用animate是否可行? - shinjidev
2
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5) 中,参数(按顺序)分别为 x 向量、y 向量、颜色、大小、透明度。尝试通过传递正确大小的 range 作为颜色参数来进行实验。一旦您喜欢的散点图绘制完成,FuncAnimation 将对它们执行与任何绘图相同的操作。 - cphlewis
2
@cphlewis 谢谢,我会玩弄这段代码以理解如何实现。真的非常感谢 :) - shinjidev
请查看https://dev59.com/gWcs5IYBdhLWcg3wSiJo#12965761。 - Warren Weckesser
@WarrenWeckesser 我尝试过使用那段代码,并得到了这段代码 https://gist.github.com/anonymous/f65d9144f66d22001fb2 。但是在每次迭代中,它都用相同的颜色绘制两个点。我想用不同的颜色绘制每个点,但是下一次迭代应该保持相同的颜色。 - shinjidev
1个回答

3

我想我明白你想做什么,是的,我认为这是可能的。首先,我设置了一些随机数据来模拟我认为你在matt中拥有的数据。

from random import random as r

numlin=50

matt = []
for j in xrange(numlin):
    matt.append([r()*20, r()*10,r()*20,r()*10])

现在,尽可能接近您的代码,我认为您想要做到这一点(我添加了一个init()函数,它只返回一个空列表,否则您的第一组点将始终留在轴上):
from matplotlib.pyplot import plot, show, subplots
import matplotlib.animation as animation

fig,ax=subplots(figsize=(20,10))
ax.set_xlim([0,20])
ax.set_ylim([0,10])


def animate(i):
    animlist = plot(matt[i][0],matt[i][1],'r',matt[i][2],matt[i][3],'b',marker='o',markersize=8)
    return animlist

def init():
    return []

anim=animation.FuncAnimation(fig,animate,frames=numlin,interval=1000,init_func=init,blit=True,repeat=0)
show()

工作原理

通过将(x0,y0,c0, x1,y1,c1, x2,y2,c2 ... )这样的集合传递给plot()是有效的,其中cx是有效的matplotlib颜色格式。它们位于任何命名的**kwargs之前,如marker等。在文档中有描述

An arbitrary number of x, y, fmt groups can be specified, as in:

a.plot(x1, y1, 'g^', x2, y2, 'g-')

回应OP的评论进行编辑

OP希望将此功能扩展到更多的点集,而不仅仅是将它们全部附加为绘图函数的参数。以下是一种方法(修改animate()函数 - 其余部分保持不变)

def animate(i):
    #Make a tuple or list of (x0,y0,c0,x1,y1,c1,x2....)
    newpoints = (matt[i][0],matt[i][1],'r',
                 matt[i][0],matt[i][3],'b',
                 matt[i][2],matt[i][3],'g',
                 matt[i][2],matt[i][1],'y')
    # Use the * operator to expand the tuple / list
    # of (x,y,c) triplets into arguments to pass to the
    # plot function
    animlist = plot(*newpoints,marker='o',markersize=8)
    return animlist

太棒了,J Richard Snape。这正是我正在寻找的。谢谢你。只有一个小问题,是否有办法添加更多的“x,y,c”,但不用扩展调用plot方法的代码行? - shinjidev
当然 - 我会在我的答案中再编辑一些内容,向您展示我认为您想要的做法。 - J Richard Snape
非常感谢J Richard Snape,非常有帮助 :) - shinjidev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接