带有颜色渐变的 Matplotlib 3D 散点图 [英] Matplotlib 3D scatter plot with color gradient
问题描述
如何为点创建带有颜色渐变的 3D 绘图?请参阅下面的示例,该示例适用于 2D 散点图.
How can I create a 3D plot with a color gradient for the points? See the example below, which works for a 2D scatter plot.
编辑(感谢 Chris):我希望从 3D 图中看到的是从红色到绿色的点的颜色渐变,就像 2D 散点图中的一样.我在 3D 散点图中看到的只是红点.
Edit (thanks to Chris): What I'm expecting to see from the 3D plot is a color gradient of the points ranging from red to green as in the 2D scatter plot. What I see in the 3D scatter plot are only red points.
解决方案:由于某些原因(与我在别处复制的渐变示例有关),我将 xrange 设置为 len-1,这会弄乱 3D 图中的所有内容.
Solution: for some reasons (related to the gradient example I copied elsewhere) I set xrange to len-1, which messes everything in the 3D plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create Map
cm = plt.get_cmap("RdYlGn")
x = np.random.rand(30)
y = np.random.rand(30)
z = np.random.rand(30)
#col = [cm(float(i)/(29)) for i in xrange(29)] # BAD!!!
col = [cm(float(i)/(30)) for i in xrange(30)]
# 2D Plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y, s=10, c=col, marker='o')
# 3D Plot
fig = plt.figure()
ax3D = fig.add_subplot(111, projection='3d')
ax3D.scatter(x, y, z, s=10, c=col, marker='o')
plt.show()
推荐答案
以下是具有渐变颜色的 3d 散射示例:
Here is an example for 3d scatter with gradient colors:
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
def scatter3d(x,y,z, cs, colorsMap='jet'):
cm = plt.get_cmap(colorsMap)
cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c=scalarMap.to_rgba(cs))
scalarMap.set_array(cs)
fig.colorbar(scalarMap)
plt.show()
当然,您可以选择范围在不同值之间的比例,例如 0 和 1.
Of course, you can choose the scale to range between different values, like 0 and 1.
这篇关于带有颜色渐变的 Matplotlib 3D 散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!