简体   繁体   中英

Python - colormap in matplotlib for 3D line plot

I'm trying to draw a 3D line plot with the toolkits mplot3D of matplotlib I have 4 arrays

  • tab_C[0] is an array of x-value
  • tab_C[1] is an array of y-value
  • tab_C[2] is an array of z-value
  • tab_t is an array of time-value

I've draw my plot with this:

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()

It works but now I want this plot have rainbow coloring based on the time-value. I've searched the web page of matplotlib but there's nothing. Any suggestion on this problem?

You can do it in pure matploblib fashion as Bill shows, but it is more intuitive with Mayavi . Here is a nice example from their documentation:

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')

在此输入图像描述

It is just the argument colormap that determines the colormap , and x , y , z , t can be replaced by the particular array that you want.

There is no easy, "one-liner" way to do this. However, one way forward isn't so bad. The only thing you need to think about is how to map your time values to colors. Here's one possible way to proceed:

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()

在此输入图像描述

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])

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()

However, the depends on how you defined your time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM