[英]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
的数组x
、 y
、 z
和T
,我想使用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:我在网上找到的:
cmap
with scatter
like shown in the docs and in this stackoverflow question可以将cmap
与scatter
一起使用,如文档和此 stackoverflow 问题中所示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
是一组点,而不是曲线。
n-1
intervals and each interval we use a different color like在这个 stackoverflow 问题中,解决方案分为n-1
区间,每个区间我们使用不同的颜色,例如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:这是食谱:
Line3DCollection
object.创建一个Line3DCollection
对象。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.