带Colorb的Matplotlib三维散点图

2024-05-12 13:15:55 发布

您现在位置:Python中文网/ 问答频道 /正文

从Matplotlib文档页面的example中借用并稍微修改代码

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()

将为每个点提供具有不同颜色的三维散点图(本例中为随机颜色)。向图中添加颜色条的正确方法是什么,因为添加plt.colorbar()ax.colorbar()似乎不起作用。


Tags: import颜色asnpfigpltaxlabel
1条回答
网友
1楼 · 发布于 2024-05-12 13:15:55

这会产生一个颜色条(尽管可能不是您需要的颜色条):

替换此行:

ax.scatter(xs, ys, zs, c=cs, marker=m)

p = ax.scatter(xs, ys, zs, c=cs, marker=m)

然后使用

fig.colorbar(p)

接近尾声

相关问题 更多 >