python matplotlib.pyplot中3D参数曲线的线条颜色 [英] Line colour of 3D parametric curve in python's matplotlib.pyplot

查看:757
本文介绍了python matplotlib.pyplot中3D参数曲线的线条颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了很长时间,但没有成功...也许我的关键字太糟糕了.无论如何,假设我有三个相同长度的1D numpy.ndarray,我想将它们绘制在3D中作为轨迹.此外,我希望能够执行以下任一操作:

I've been googling quite some time with no success ... maybe my keywords are just lousy. Anyway, suppose I have three 1D numpy.ndarrays of the same length I'd like to plot them in 3D as a trajectory. Moreover, I'd like to be able to do either of the following things:

  1. 根据z
  2. 更改线条的颜色
  3. 根据时间(即数组中的索引)更改线条的颜色
  1. Change the colour of the line as a function of z
  2. Change the colour of the line as a function of time (i.e. the index in the arrays)

此演示具有绘制此类曲线的示例:

This demo has an example of making such a curve:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z)

plt.show()

但是如何实现12?欢迎只解决其中一个问题! 预先感谢.

But how do I achieve 1 or 2? Solutions to only one or the other are welcome! Thanks in advance.

推荐答案

与普通2d图一样,沿着普通线不能有颜色渐变.但是,您可以使用scatter:

As with normal 2d plots, you cannot have a gradient of color along an ordinary line. However, you can do it with scatter:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

#1 colored by value of `z`
ax.scatter(x, y, z, c = plt.cm.jet(z/max(z))) 

#2 colored by index (same in this example since z is a linspace too)
N = len(z)
ax.scatter(x, y, z, c = plt.cm.jet(np.linspace(0,1,N)))

plt.show()


我喜欢 @Junuxx的 hack ,所以我在这里应用了它:


I liked @Junuxx's hack so I applied it here:

for i in xrange(N-1):
    ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(255*i/N))

这篇关于python matplotlib.pyplot中3D参数曲线的线条颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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