带颜色条的 Matplotlib 3D 散点图 [英] Matplotlib 3D Scatter Plot with Colorbar
本文介绍了带颜色条的 Matplotlib 3D 散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
借用 Matplotlib 文档页面上的 示例 和稍微修改一下代码,
Borrowing from the example on the Matplotlib documentation page and slightly modifying the code,
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()
似乎不起作用.
Will give a 3D scatter plot with different colors for each point (random colors in this example). What's the correct way to add a colorbar to the figure, since adding in plt.colorbar()
or ax.colorbar()
doesn't seem to work.
推荐答案
这会产生一个颜色条(虽然可能不是你需要的):
This produces a colorbar (though possibly not the one you need):
替换这一行:
ax.scatter(xs, ys, zs, c=cs, marker=m)
与
p = ax.scatter(xs, ys, zs, c=cs, marker=m)
然后使用
fig.colorbar(p)
接近尾声
这篇关于带颜色条的 Matplotlib 3D 散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文