簡體   English   中英

在 matplotlib 中為 3D 曲線着色

[英]Colormap a 3D curve in matplotlib

我有 4 個長度為n的數組xyzT ,我想使用matplotlib繪制 3D 曲線。 (x, y, z)是點位置, T是每個點的值(以顏色繪制),例如每個點的溫度。 我該怎么做?

示例代碼:

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]

我在網上找到的:

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

問題是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])

問題是每個段只有一種顏色,但應該是漸變色。 甚至沒有使用最后一個值。

有用的鏈接:

在這種情況下,您可能需要使用Line3DCollection 這是食譜:

  1. 從您的坐標數組創建線段。
  2. 創建一個Line3DCollection對象。
  3. 將該集合添加到軸。
  4. 設置軸限制。
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