简体   繁体   English

在 matplotlib 中为 3D 曲线着色

[英]Colormap a 3D curve in matplotlib

I have 4 arrays x , y , z and T of length n and I want to plot a 3D curve using matplotlib .我有 4 个长度为n的数组xyzT ,我想使用matplotlib绘制 3D 曲线。 The (x, y, z) are the points positions and T is the value of each point (which is plotted as color), like the temperature of each point. (x, y, z)是点位置, T是每个点的值(以颜色绘制),例如每个点的温度。 How can I do it?我该怎么做?

Example code:示例代码:

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
n = 100
cmap = plt.get_cmap("bwr")
theta = np.linspace(-4 * np.pi, 4 * np.pi, n)
z = np.linspace(-2, 2, n)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
T = (2*np.random.rand(n) - 1)  # All the values are in [-1, 1]

What I found over the internet:我在网上找到的:

ax = plt.gca()
ax.scatter(x, y, z, cmap=cmap, c=T)

The problem is that scatter is a set of points, not a curve.问题是scatter是一组点,而不是曲线。

t = (T - np.min(T))/(np.max(T)-np.min(T))  # Normalize
for i in range(n-1):
    plt.plot(x[i:i+2], y[i:i+2], z[i:i+2], c=cmap(t[i])

The problem is that each segment has only one color, but it should be an gradient.问题是每个段只有一种颜色,但应该是渐变色。 The last value is not even used.甚至没有使用最后一个值。

Useful links:有用的链接:

This is a case where you probably need to use Line3DCollection .在这种情况下,您可能需要使用Line3DCollection This is the recipe:这是食谱:

  1. create segments from your array of coordinates.从您的坐标数组创建线段。
  2. create a Line3DCollection object.创建一个Line3DCollection对象。
  3. add that collection to the axis.将该集合添加到轴。
  4. set the axis limits.设置轴限制。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize

def get_segments(x, y, z):
    """Convert lists of coordinates to a list of segments to be used
    with Matplotlib's Line3DCollection.
    """
    points = np.ma.array((x, y, z)).T.reshape(-1, 1, 3)
    return np.ma.concatenate([points[:-1], points[1:]], axis=1)

fig = plt.figure()
ax = fig.add_subplot(projection='3d')
n = 100
cmap = plt.get_cmap("bwr")
theta = np.linspace(-4 * np.pi, 4 * np.pi, n)
z = np.linspace(-2, 2, n)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
T = np.cos(theta)

segments = get_segments(x, y, z)
c = Line3DCollection(segments, cmap=cmap, array=T)
ax.add_collection(c)
fig.colorbar(c)

ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
ax.set_zlim(z.min(), z.max())
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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