Matplotlib 动画:绘制不同颜色的线条 [英] Matplotlib animation: draw lines in different colours

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

问题描述

我现在有以下代码来显示曲线的增长:

I have the following code right now, to show growth of a curve:

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation

def move_curve(i, line, x, y, z):
    # Add points rather than changing start and end points.
    line.set_data(x[:i+1], y[:i+1])
    line.set_3d_properties(z[:i+1])

fig = plt.figure()
ax = fig.gca(projection='3d')
x = [1, 3, 8, 11, 17]
y = [7, 2, -5, 3, 5]
z = [5, 7, 9, 13, 18]

i = 0
line = ax.plot([x[i], x[i+1]], [y[i],y[i+1]], [z[i],z[i+1]])[0]
ax.set_xlim3d([1, 17])
ax.set_ylim3d([-5, 7])
ax.set_zlim3d([5, 18])

line_ani = animation.FuncAnimation(fig, move_curve, 5, fargs=(line, x, y, z))
plt.show()

我想用不同的颜色显示不同的线条.另外,我想随着曲线的增长来更新轴的长度.

I want to show the different lines in different colours. Also, I want to update the length of the axis as the curve grows.

怎么做?我是 python 的新手,所以我可能会遗漏一些简单的东西.感谢您的帮助!

How to do that? I am new to python so I might be missing something simple. Thanks for the help!

推荐答案

这是@MrT的答案在使用FuncAnimation时的样子.优点是你不需要关心自动缩放;这是即时自动完成的.

Here is how @MrT's answer would look like using FuncAnimation. The advantage is that you do not need to care about autoscaling; that is done automatically on the fly.

import matplotlib.pyplot as plt
import matplotlib.animation as anim
import mpl_toolkits.mplot3d.axes3d as p3

fig = plt.figure()
ax = fig.gca(projection='3d')

x = [1, 3, 8, 11, 17]
y = [7, 2, -5, 3, 5]
z = [5, 7, 9, 13, 18]

#colour map
colors = ["green", "blue", "red", "orange"]

def init():
    ax.clear()

def update(i): 
    newsegm, = ax.plot([x[i], x[i + 1]], [y[i], y[i + 1]], [z[i], z[i + 1]], colors[i])

ani = anim.FuncAnimation(fig, update, init_func=init, 
                         frames = range(len(x)-1), interval = 300, repeat=True)
plt.show()

这篇关于Matplotlib 动画:绘制不同颜色的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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