JC.*_*JC. 24 python 3d matplotlib scatter-plot
从借款例如在Matplotlib文档页面上,并稍微修改代码,
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
cs = randrange(n, 0, 100)
ax.scatter(xs, ys, zs, c=cs, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
Run Code Online (Sandbox Code Playgroud)
将给出每个点具有不同颜色的3D散点图(在该示例中为随机颜色).将颜色条添加到图中的正确方法是什么,因为添加plt.colorbar()
或ax.colorbar()
似乎不起作用.
mar*_*ard 30
这会产生一个颜色条(尽管可能不是你需要的颜色条):
替换此行:
ax.scatter(xs, ys, zs, c=cs, marker=m)
Run Code Online (Sandbox Code Playgroud)
同
p = ax.scatter(xs, ys, zs, c=cs, marker=m)
Run Code Online (Sandbox Code Playgroud)
然后用
fig.colorbar(p)
Run Code Online (Sandbox Code Playgroud)
接近尾声
Pad*_*son 11
使用上面的答案并没有解决我的问题。颜色条颜色图未链接到轴(另请注意不正确的颜色条限制):
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
data = np.random.rand(3, 100)
x, y, z = data # for show
c = np.arange(len(x)) / len(x) # create some colours
p = ax.scatter(x, y, z, c=plt.cm.magma(0.5*c))
ax.set_xlabel('$\psi_1$')
ax.set_ylabel('$\Phi$')
ax.set_zlabel('$\psi_2$')
ax.set_box_aspect([np.ptp(i) for i in data]) # equal aspect ratio
fig.colorbar(p, ax=ax)
Run Code Online (Sandbox Code Playgroud)
解决方案(另见此处)是cmap
使用ax.scatter
:
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
data = np.random.rand(3, 100)
x, y, z = data # for show
c = np.arange(len(x)) / len(x) # create some colours
p = ax.scatter(x, y, z, c=0.5*c, cmap=plt.cm.magma)
ax.set_xlabel('$\psi_1$')
ax.set_ylabel('$\Phi$')
ax.set_zlabel('$\psi_2$')
ax.set_box_aspect([np.ptp(i) for i in data]) # equal aspect ratio
fig.colorbar(p, ax=ax)
Run Code Online (Sandbox Code Playgroud)