Matplotlib 3D Scatter Plot with Colorbar

JC. picture JC. · Mar 31, 2011 · Viewed 31.6k times · Source

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.

Answer

marshall.ward picture marshall.ward · Mar 31, 2011

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