在matplotlib动画中用不同颜色打印点

2024-05-16 06:05:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码:

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中执行此操作?在


Tags: 代码plotmatplotlib颜色showfig绘制matt
1条回答
网友
1楼 · 发布于 2024-05-16 06:05:15

我想我知道你想做什么,是的,我认为这是可能的。首先,我设置了一些随机数据来模拟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()函数,它只返回一个空列表,否则您的第一组点始终保持在轴上):

^{2}$

工作原理

(x0,y0,c0, x1,y1,c1, x2,y2,c2 ... )集传入plot()是有效的,其中cx是有效的matplotlib颜色格式。它们位于任何名为**kwargs的前面,如markerIt's described in the docs here。在

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

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

编辑回应OP评论

OP想让这个扩展到更多的点集,而不是简单地将它们作为参数附加到plot函数中。这里有一种方法(改变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

相关问题 更多 >