Python - matplotlib中的colormap用于3D线图

pom*_*pum 4 python matplotlib colormap

我正在尝试使用matplotlib的工具包mplot3D绘制3D线图我有4个数组

  • tab_C [0]是x值的数组
  • tab_C [1]是y值的数组
  • tab_C [2]是一个z值数组
  • tab_t是一个时间值数组

我用这个绘制了我的情节:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig1 = plt.figure()
ax = fig1.gca(projection='3d')
ax.plot(tab_C[0], tab_C[1], tab_C[2])

plt.show()
Run Code Online (Sandbox Code Playgroud)

它工作但现在我希望这个情节有基于时间值的彩虹色.我搜索了matplotlib的网页,但没有任何内容.有关这个问题的任何建议吗?

wfl*_*nny 5

没有简单的“单行”方法可以做到这一点。然而,前进的一种方式并没有那么糟糕。您唯一需要考虑的是如何将时间值映射到颜色。这是一种可行的方法:

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

N_points = 10
x = np.arange(N_points, dtype=float)
y = x
z = np.random.rand(N_points)
t = x

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

# colors need to be 3-tuples with values between 0-1.
# if you want to use the time values directly, you could do something like
t /= max(t)
for i in range(1, N_points):
    ax.plot(x[i-1:i+1], y[i-1:i+1], z[i-1:i+1], c=(t[i-1], 0, 0))
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

You can play around with that tuple. Having one value with 2 zeros will give you shades of red, green and blue depending on the position of the nonzero argument. Some other possible color choices could be shades of gray

c = (t[i-1], t[i-1], t[i-1])
Run Code Online (Sandbox Code Playgroud)

or instead cycling through a list of predefined colors:

# Don't do: t /= max(t)
from itertools import cycle
colors = cycle('bgrc')
for i in range(1, N_points):
    ax.plot(x[i-1:i+1], y[i-1:i+1], z[i-1:i+1], c=colors[t[i-1]])
plt.show()
Run Code Online (Sandbox Code Playgroud)

However, the depends on how you defined your time.


osc*_*ury 5

你可以像Bill所展示的那样以纯matploblib的方式做到这一点,但它对Mayavi来说更直观.这是他们的文档中的一个很好的例子:

from mayavi import mlab
n_mer, n_long = 6, 11
dphi = np.pi / 1000.0
phi = np.arange(0.0, 2 * pi + 0.5 * dphi, dphi)
mu = phi * n_mer
x = np.cos(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5)
y = np.sin(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5)
z = np.sin(n_long * mu / n_mer) * 0.5
t = np.sin(mu)

mlab.plot3d(x, y, z, t, tube_radius=0.025, colormap='Spectral')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这仅仅是参数colormap决定了颜色表,和x,y,z,t可以通过所需的特定的阵列来代替.