带有Colorbar的Matplotlib 3D散点图

问题描述 投票:24回答:2

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

将为每个点提供不同颜色的3D散点图(在此示例中为随机颜色)。向图中添加颜色条的正确方法是什么,因为添加plt.colorbar()ax.colorbar()似乎无效。

python 3d matplotlib scatter-plot
2个回答
30
投票

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

替换此行:

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

with

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

然后使用

fig.colorbar(p)

接近尾声


0
投票

我有一个问题。当我想捕获cbar对象并更改其限制时,它会给出不建议使用的警告。

MatplotlibDeprecation警告:在Matplotlib 3.1中已弃用set_clim函数,并将在3.3中将其删除。请改用ScalarMappable.set_clim。

cbar = fig.colorbar(p)
cbar.set_clim(0,1)

并且颜色栏不变。还有其他方法可以更改cbar限制吗?

© www.soinside.com 2019 - 2024. All rights reserved.