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()
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.
Three-dimensional plotting is one of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; recall that to use interactive figures, you can use %matplotlib notebook rather than %matplotlib inline when running this code.
This produces a colorbar (though possibly not the one you need):
Replace this line:
ax.scatter(xs, ys, zs, c=cs, marker=m)
with
p = ax.scatter(xs, ys, zs, c=cs, marker=m)
then use
fig.colorbar(p)
near the end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With